Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More ruff #1431

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,12 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import sys
from os import environ
from os.path import abspath, join
from pprint import pprint
from sys import path


path.insert(0, abspath(join("..", "src")))

pprint(environ)
pprint(sys.path)


# -- Project information -----------------------------------------------------

Expand Down
31 changes: 8 additions & 23 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ ignore = [
"RSE102", # Unnecessary parentheses on raised exception
"S101", # Use of `assert` detected
"S608", # Possible SQL injection vector through string-based query construction
"SIM108", # Use ternary operator
"SIM118", # Use `key in dict` instead of `key in dict.keys()`
"TD001", # Invalid TODO tag: `FIXME`
"TD002", # Missing author in TODO
"TD003", # Missing issue link on the line following this TODO
"TRY003", # Avoid specifying long messages outside the exception class
"TRY301", # Abstract `raise` to an inner function
"TRY400", # Use `logging.exception` instead of `logging.error`

# Reconsider
"TID252", # Prefer absolute imports over relative imports from parent modules
Expand All @@ -130,30 +138,7 @@ ignore = [
"FBT001", # Boolean-typed positional argument in function definition
"FBT002", # Boolean default positional argument in function definition
"FBT003", # Boolean positional value in function call
"SIM102", # Use a single `if` statement instead of nested `if` statements
"SIM105", # Use `contextlib.suppress(NoSectionError, NoOptionError)` instead of `try`-`except`-`pass`
"SIM108", # Use ternary operator
"SIM114", # Combine `if` branches using logical `or` operator
"SIM115", # Use a context manager for opening files
"SIM118", # Use `key in dict` instead of `key in dict.keys()`
"SLF001", # Private member accessed
"T201", # `print` found
"T203", # `pprint` found
"TC001", # Move application import into a type-checking block
"TC003", # Move standard library import into a type-checking block
"TD001", # Invalid TODO tag: `FIXME`
"TD002", # Missing author in TODO
"TD003", # Missing issue link on the line following this TODO
"TRY003", # Avoid specifying long messages outside the exception class
"TRY301", # Abstract `raise` to an inner function
"TRY400", # Use `logging.exception` instead of `logging.error`
"UP006", # Use `collections.deque` instead of `Deque` for type annotation
"UP007", # Use `X | Y` for type annotations
"UP017", # Use `datetime.UTC` alias
"UP031", # Use format specifiers instead of percent format
"UP032", # Use f-string instead of `format` call
"UP035", # `typing.Deque` is deprecated, use `collections.deque` instead
"UP038", # Use `X | Y` in `isinstance` call instead of `(X, Y)`
]

[tool.ruff.lint.isort]
Expand Down
10 changes: 5 additions & 5 deletions src/ims/application/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
Iterable,
Mapping,
)
from datetime import UTC

Check warning on line 28 in src/ims/application/_api.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_api.py#L28

Added line #L28 was not covered by tests
from datetime import datetime as DateTime
from datetime import timezone as TimeZone
from enum import Enum
from functools import partial
from json import JSONDecodeError
Expand Down Expand Up @@ -405,7 +405,7 @@

user: IMSUser = request.user # type: ignore[attr-defined]
author = user.shortNames[0]
now = DateTime.now(TimeZone.utc)
now = DateTime.now(UTC)

Check warning on line 408 in src/ims/application/_api.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_api.py#L408

Added line #L408 was not covered by tests
jsonNow = jsonObjectFromModelObject(now)

# Set JSON incident number to 0
Expand Down Expand Up @@ -662,7 +662,7 @@

jsonEntries = edits.get(IncidentJSONKey.reportEntries.value, UNSET)
if jsonEntries is not UNSET:
now = DateTime.now(TimeZone.utc)
now = DateTime.now(UTC)

Check warning on line 665 in src/ims/application/_api.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_api.py#L665

Added line #L665 was not covered by tests

entries = (
ReportEntry(
Expand Down Expand Up @@ -769,7 +769,7 @@

user: IMSUser = request.user # type: ignore[attr-defined]
author = user.shortNames[0]
now = DateTime.now(TimeZone.utc)
now = DateTime.now(UTC)

Check warning on line 772 in src/ims/application/_api.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_api.py#L772

Added line #L772 was not covered by tests
jsonNow = jsonObjectFromModelObject(now)

# Set JSON event id
Expand Down Expand Up @@ -980,7 +980,7 @@

jsonEntries = edits.get(IncidentReportJSONKey.reportEntries.value, UNSET)
if jsonEntries is not UNSET:
now = DateTime.now(TimeZone.utc)
now = DateTime.now(UTC)

Check warning on line 983 in src/ims/application/_api.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_api.py#L983

Added line #L983 was not covered by tests

entries = (
ReportEntry(
Expand Down
4 changes: 2 additions & 2 deletions src/ims/application/_eventsource.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from collections import deque
from collections.abc import Mapping
from time import time
from typing import Any, ClassVar, Deque
from typing import Any, ClassVar

Check warning on line 24 in src/ims/application/_eventsource.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_eventsource.py#L24

Added line #L24 was not covered by tests

from attrs import field, frozen
from twisted.logger import ILogObserver, Logger
Expand Down Expand Up @@ -76,7 +76,7 @@
_log: ClassVar[Logger] = Logger()

_listeners: list[IRequest] = field(init=False, factory=list)
_events: Deque[tuple[int, Event]] = field(
_events: deque[tuple[int, Event]] = field(
init=False, factory=lambda: deque(maxlen=1000)
)
_start: float = field(init=False, factory=time)
Expand Down
16 changes: 9 additions & 7 deletions src/ims/application/_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,11 @@
def connectionMade(self):
method = _ensureValidMethod(getattr(self.factory, "method", b"GET"))
self.sendCommand(method, _ensureValidURI(self.factory.path))
if self.factory.scheme == b"http" and self.factory.port != 80: # noqa: PLR2004
host = b"%b:%d" % (self.factory.host, self.factory.port)
elif self.factory.scheme == b"https" and self.factory.port != 443: # noqa: PLR2004
if (
self.factory.scheme == b"http" and self.factory.port != 80 # noqa: PLR2004
) or (
self.factory.scheme == b"https" and self.factory.port != 443 # noqa: PLR2004
):
host = b"%b:%d" % (self.factory.host, self.factory.port)
else:
host = self.factory.host
Expand Down Expand Up @@ -259,8 +261,8 @@
self.transport.abortConnection()
self.factory.noPage(
defer.TimeoutError(
"Getting %s took longer than %s seconds."
% (self.factory.url, self.factory.timeout)
f"Getting {self.factory.url} took longer than "
f"{self.factory.timeout} seconds."
)
)

Expand Down Expand Up @@ -548,10 +550,10 @@

def openFile(self, partialContent):
if partialContent:
file = open(self.fileName, "rb+")
file = open(self.fileName, "rb+") # noqa: SIM115

Check warning on line 553 in src/ims/application/_external.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_external.py#L553

Added line #L553 was not covered by tests
file.seek(0, 2)
else:
file = open(self.fileName, "wb")
file = open(self.fileName, "wb") # noqa: SIM115

Check warning on line 556 in src/ims/application/_external.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_external.py#L556

Added line #L556 was not covered by tests
return file

def pageStart(self, partialContent):
Expand Down
11 changes: 5 additions & 6 deletions src/ims/application/_klein.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from collections.abc import Callable, Iterable, Sequence
from functools import wraps
from typing import Any, Optional, TypeVar, cast
from typing import Any, TypeVar, cast

Check warning on line 23 in src/ims/application/_klein.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_klein.py#L23

Added line #L23 was not covered by tests

from hyperlink import URL
from klein import Klein, KleinRenderable, KleinRouteHandler
Expand Down Expand Up @@ -274,7 +274,7 @@
C{default} if there no such query parameter.
If more than one value is found, return the last value found.
"""
values = cast(Optional[Sequence[bytes]], request.args.get(name.encode("utf-8")))
values = cast(Sequence[bytes] | None, request.args.get(name.encode("utf-8")))

Check warning on line 277 in src/ims/application/_klein.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_klein.py#L277

Added line #L277 was not covered by tests

if values is None:
return default
Expand All @@ -301,7 +301,7 @@
@return: The values of the query parameter specified by C{name}, or
C{default} if there no such query parameter.
"""
values = cast(Optional[Sequence[bytes]], request.args.get(name))
values = cast(Sequence[bytes] | None, request.args.get(name))

Check warning on line 304 in src/ims/application/_klein.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_klein.py#L304

Added line #L304 was not covered by tests

if values is None:
return default
Expand Down Expand Up @@ -439,9 +439,8 @@
Not authenticated.
"""
requestedWith = request.getHeader("X-Requested-With")
if requestedWith is not None:
if requestedWith == "XMLHttpRequest":
return forbiddenResponse(request)
if requestedWith == "XMLHttpRequest":
return forbiddenResponse(request)

Check warning on line 443 in src/ims/application/_klein.py

View check run for this annotation

Codecov / codecov/patch

src/ims/application/_klein.py#L443

Added line #L443 was not covered by tests

element = redirect(request, URLs.login, origin="o")
return renderElement( # type: ignore[return-value]
Expand Down
5 changes: 2 additions & 3 deletions src/ims/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from collections.abc import Callable, Sequence
from configparser import ConfigParser, NoOptionError, NoSectionError
from contextlib import suppress
from datetime import timedelta as TimeDelta
from functools import partial
from os import environ
Expand Down Expand Up @@ -110,10 +111,8 @@ def valueFromConfig(
value = environ.get(f"IMS_{variable}")

if not value:
try:
with suppress(NoSectionError, NoOptionError):
value = self._configParser.get(section, option)
except (NoSectionError, NoOptionError):
pass

if value:
return value
Expand Down
2 changes: 1 addition & 1 deletion src/ims/directory/clubhouse_db/_dms.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ async def personnel(self) -> Iterable[Ranger]:
self._state._dbpool = None
self._state._dbErrorCount += 1

if isinstance(e, (SQLDatabaseError, SQLOperationalError)):
if isinstance(e, SQLDatabaseError | SQLOperationalError):
if self._state._dbErrorCount < 2: # noqa: PLR2004
self._log.info(
"Retrying loading personnel from DMS "
Expand Down
7 changes: 5 additions & 2 deletions src/ims/directory/clubhouse_db/test/dummy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
Mock objects for Clubhouse directory.
"""

from collections.abc import MutableSequence
from typing import Any, cast
from typing import TYPE_CHECKING, Any, cast

from twisted.internet.defer import Deferred, fail, succeed

Expand All @@ -28,6 +27,10 @@
from ..._directory import hashPassword


if TYPE_CHECKING:
from collections.abc import MutableSequence


__all__ = ()


Expand Down
2 changes: 1 addition & 1 deletion src/ims/ext/klein.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from ims.ext.enum import Enum, Names, auto

from .. import __version__ as version
from .. import __version__ as version # noqa: TC001


__all__ = (
Expand Down
6 changes: 3 additions & 3 deletions src/ims/ext/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from sqlite3 import Row as BaseRow
from sqlite3 import connect as sqliteConnect
from types import TracebackType
from typing import Any, ClassVar, Optional, TextIO, Union, cast
from typing import Any, ClassVar, TextIO, cast

from attrs import frozen
from twisted.logger import Logger
Expand All @@ -35,7 +35,7 @@

CursorFactory = Callable[..., "Cursor"]

ParameterValue = Optional[Union[bytes, str, int, float]]
ParameterValue = bytes | str | int | float | None
Parameters = Mapping[str, ParameterValue]

SQLITE_MIN_INT = -(2**63) # 64 bits
Expand Down Expand Up @@ -112,7 +112,7 @@ def executeAndPrint(self, sql: str, parameters: Parameters | None = None) -> Non
"""

def emit(row: Iterable[object]) -> None:
print(" | ".join(str(i) for i in row))
print(" | ".join(str(i) for i in row)) # noqa: T201

printHeader = True

Expand Down
9 changes: 3 additions & 6 deletions src/ims/model/_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,9 @@ def _cmp(self, other: Any, methodName: str) -> bool:
if other is None:
return self._allNone()

if other.__class__ is TextOnlyAddress:
if self._allNone():
method = cast(
Callable[[str], bool], getattr(self.description, methodName)
)
return method(other.description)
if other.__class__ is TextOnlyAddress and self._allNone():
method = cast(Callable[[str], bool], getattr(self.description, methodName))
return method(other.description)

return ComparisonMixIn._cmp(self, other, methodName)

Expand Down
10 changes: 5 additions & 5 deletions src/ims/model/json/_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"""

from enum import Enum, unique
from typing import Any, Optional, cast
from typing import Any, cast

from .._address import Address, RodGarettAddress, TextOnlyAddress
from ._json import (
Expand Down Expand Up @@ -63,7 +63,7 @@ class AddressJSONType(Enum):
"""

addressType = str
description = cast(type[Any], Optional[str])
description = cast(type[Any], str | None)


@unique
Expand Down Expand Up @@ -100,9 +100,9 @@ class RodGarettAddressJSONType(Enum):
Rod Garett address JSON keys
"""

concentric = Optional[str]
radialHour = Optional[int]
radialMinute = Optional[int]
concentric = str | None
radialHour = int | None
radialMinute = int | None
description = AddressJSONType.description.value


Expand Down
4 changes: 2 additions & 2 deletions src/ims/model/json/_incident.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from datetime import datetime as DateTime
from enum import Enum, unique
from typing import Any, Optional, cast
from typing import Any, cast

from .._entry import ReportEntry
from .._incident import Incident
Expand Down Expand Up @@ -67,7 +67,7 @@ class IncidentJSONType(Enum):
created = DateTime
state = IncidentState
priority = IncidentPriority
summary = Optional[str]
summary = str | None
location = Location
rangerHandles = set[str]
incidentTypes = set[str]
Expand Down
4 changes: 2 additions & 2 deletions src/ims/model/json/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from collections.abc import Callable, Iterable, Mapping
from datetime import datetime as DateTime
from enum import Enum
from typing import Any, Union, cast
from typing import Any, cast

from cattr import Converter
from twisted.logger import Logger
Expand All @@ -36,7 +36,7 @@
log = Logger()


JSON = Union[Mapping[str, Any], Iterable[Any], int, str, float, bool, None]
JSON = Mapping[str, Any] | Iterable[Any] | int | str | float | bool | None


class JSONCodecError(Exception):
Expand Down
4 changes: 2 additions & 2 deletions src/ims/model/json/_ranger.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"""

from enum import Enum, unique
from typing import Any, Optional, cast
from typing import Any, cast

from .._ranger import Ranger, RangerStatus
from ._json import (
Expand Down Expand Up @@ -58,7 +58,7 @@ class RangerJSONType(Enum):
status = RangerStatus
# email is intentionally not serialized, since no web client needs it
enabled = bool
directoryID = Optional[str]
directoryID = str | None
# password is intentionally not serialized, since no web client needs it


Expand Down
Loading
Loading