Skip to content

Commit 992d150

Browse files
authored
PYTHON-4005 Replace flake8 and isort with ruff (#1399)
1 parent 1f7b74f commit 992d150

File tree

189 files changed

+634
-454
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

189 files changed

+634
-454
lines changed

.flake8

Lines changed: 0 additions & 30 deletions
This file was deleted.

.pre-commit-config.yaml

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,12 @@ repos:
2424
files: \.py$
2525
args: [--line-length=100]
2626

27-
- repo: https://github.com/PyCQA/isort
28-
rev: 5.12.0
27+
- repo: https://github.com/astral-sh/ruff-pre-commit
28+
# Ruff version.
29+
rev: v0.1.0
2930
hooks:
30-
- id: isort
31-
files: \.py$
32-
args: [--profile=black]
31+
- id: ruff
32+
args: ["--fix", "--show-fixes"]
3333

3434
- repo: https://github.com/adamchainz/blacken-docs
3535
rev: "1.13.0"
@@ -38,18 +38,6 @@ repos:
3838
additional_dependencies:
3939
- black==22.3.0
4040

41-
- repo: https://github.com/PyCQA/flake8
42-
rev: 3.9.2
43-
hooks:
44-
- id: flake8
45-
files: \.py$
46-
additional_dependencies: [
47-
'flake8-bugbear==20.1.4',
48-
'flake8-logging-format==0.6.0',
49-
'flake8-implicit-str-concat==0.2.0',
50-
]
51-
stages: [manual]
52-
5341
# We use the Python version instead of the original version which seems to require Docker
5442
# https://github.com/koalaman/shellcheck-precommit
5543
- repo: https://github.com/shellcheck-py/shellcheck-py

bson/__init__.py

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def _raise_unknown_type(element_type: int, element_name: str) -> NoReturn:
244244

245245

246246
def _get_int(
247-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
247+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
248248
) -> Tuple[int, int]:
249249
"""Decode a BSON int32 to python int."""
250250
return _UNPACK_INT_FROM(data, position)[0], position + 4
@@ -257,7 +257,7 @@ def _get_c_string(data: Any, view: Any, position: int, opts: CodecOptions[Any])
257257

258258

259259
def _get_float(
260-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
260+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
261261
) -> Tuple[float, int]:
262262
"""Decode a BSON double to python float."""
263263
return _UNPACK_FLOAT_FROM(data, position)[0], position + 8
@@ -282,7 +282,7 @@ def _get_object_size(data: Any, position: int, obj_end: int) -> Tuple[int, int]:
282282
try:
283283
obj_size = _UNPACK_INT_FROM(data, position)[0]
284284
except struct.error as exc:
285-
raise InvalidBSON(str(exc))
285+
raise InvalidBSON(str(exc)) from None
286286
end = position + obj_size - 1
287287
if data[end] != 0:
288288
raise InvalidBSON("bad eoo")
@@ -358,7 +358,7 @@ def _get_array(
358358

359359

360360
def _get_binary(
361-
data: Any, view: Any, position: int, obj_end: int, opts: CodecOptions[Any], dummy1: Any
361+
data: Any, _view: Any, position: int, obj_end: int, opts: CodecOptions[Any], dummy1: Any
362362
) -> Tuple[Union[Binary, uuid.UUID], int]:
363363
"""Decode a BSON binary to bson.binary.Binary or python UUID."""
364364
length, subtype = _UNPACK_LENGTH_SUBTYPE_FROM(data, position)
@@ -395,15 +395,15 @@ def _get_binary(
395395

396396

397397
def _get_oid(
398-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
398+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
399399
) -> Tuple[ObjectId, int]:
400400
"""Decode a BSON ObjectId to bson.objectid.ObjectId."""
401401
end = position + 12
402402
return ObjectId(data[position:end]), end
403403

404404

405405
def _get_boolean(
406-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
406+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
407407
) -> Tuple[bool, int]:
408408
"""Decode a BSON true/false to python True/False."""
409409
end = position + 1
@@ -416,7 +416,7 @@ def _get_boolean(
416416

417417

418418
def _get_date(
419-
data: Any, view: Any, position: int, dummy0: int, opts: CodecOptions[Any], dummy1: Any
419+
data: Any, _view: Any, position: int, dummy0: int, opts: CodecOptions[Any], dummy1: Any
420420
) -> Tuple[Union[datetime.datetime, DatetimeMS], int]:
421421
"""Decode a BSON datetime to python datetime.datetime."""
422422
return _millis_to_datetime(_UNPACK_LONG_FROM(data, position)[0], opts), position + 8
@@ -431,7 +431,7 @@ def _get_code(
431431

432432

433433
def _get_code_w_scope(
434-
data: Any, view: Any, position: int, obj_end: int, opts: CodecOptions[Any], element_name: str
434+
data: Any, view: Any, position: int, _obj_end: int, opts: CodecOptions[Any], element_name: str
435435
) -> Tuple[Code, int]:
436436
"""Decode a BSON code_w_scope to bson.code.Code."""
437437
code_end = position + _UNPACK_INT_FROM(data, position)[0]
@@ -462,22 +462,22 @@ def _get_ref(
462462

463463

464464
def _get_timestamp(
465-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
465+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
466466
) -> Tuple[Timestamp, int]:
467467
"""Decode a BSON timestamp to bson.timestamp.Timestamp."""
468468
inc, timestamp = _UNPACK_TIMESTAMP_FROM(data, position)
469469
return Timestamp(timestamp, inc), position + 8
470470

471471

472472
def _get_int64(
473-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
473+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
474474
) -> Tuple[Int64, int]:
475475
"""Decode a BSON int64 to bson.int64.Int64."""
476476
return Int64(_UNPACK_LONG_FROM(data, position)[0]), position + 8
477477

478478

479479
def _get_decimal128(
480-
data: Any, view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
480+
data: Any, _view: Any, position: int, dummy0: Any, dummy1: Any, dummy2: Any
481481
) -> Tuple[Decimal128, int]:
482482
"""Decode a BSON decimal128 to bson.decimal128.Decimal128."""
483483
end = position + 16
@@ -496,11 +496,11 @@ def _get_decimal128(
496496
ord(BSONOBJ): _get_object,
497497
ord(BSONARR): _get_array,
498498
ord(BSONBIN): _get_binary,
499-
ord(BSONUND): lambda u, v, w, x, y, z: (None, w), # Deprecated undefined
499+
ord(BSONUND): lambda u, v, w, x, y, z: (None, w), # noqa: ARG005 # Deprecated undefined
500500
ord(BSONOID): _get_oid,
501501
ord(BSONBOO): _get_boolean,
502502
ord(BSONDAT): _get_date,
503-
ord(BSONNUL): lambda u, v, w, x, y, z: (None, w),
503+
ord(BSONNUL): lambda u, v, w, x, y, z: (None, w), # noqa: ARG005
504504
ord(BSONRGX): _get_regex,
505505
ord(BSONREF): _get_ref, # Deprecated DBPointer
506506
ord(BSONCOD): _get_code,
@@ -510,16 +510,16 @@ def _get_decimal128(
510510
ord(BSONTIM): _get_timestamp,
511511
ord(BSONLON): _get_int64,
512512
ord(BSONDEC): _get_decimal128,
513-
ord(BSONMIN): lambda u, v, w, x, y, z: (MinKey(), w),
514-
ord(BSONMAX): lambda u, v, w, x, y, z: (MaxKey(), w),
513+
ord(BSONMIN): lambda u, v, w, x, y, z: (MinKey(), w), # noqa: ARG005
514+
ord(BSONMAX): lambda u, v, w, x, y, z: (MaxKey(), w), # noqa: ARG005
515515
}
516516

517517

518518
if _USE_C:
519519

520520
def _element_to_dict(
521521
data: Any,
522-
view: Any,
522+
view: Any, # noqa: ARG001
523523
position: int,
524524
obj_end: int,
525525
opts: CodecOptions[Any],
@@ -615,11 +615,11 @@ def _bson_to_dict(data: Any, opts: CodecOptions[_DocumentType]) -> _DocumentType
615615
except Exception:
616616
# Change exception type to InvalidBSON but preserve traceback.
617617
_, exc_value, exc_tb = sys.exc_info()
618-
raise InvalidBSON(str(exc_value)).with_traceback(exc_tb)
618+
raise InvalidBSON(str(exc_value)).with_traceback(exc_tb) from None
619619

620620

621621
if _USE_C:
622-
_bson_to_dict = _cbson._bson_to_dict # noqa: F811
622+
_bson_to_dict = _cbson._bson_to_dict
623623

624624

625625
_PACK_FLOAT = struct.Struct("<d").pack
@@ -653,7 +653,9 @@ def _make_c_string_check(string: Union[str, bytes]) -> bytes:
653653
_utf_8_decode(string, None, True)
654654
return string + b"\x00"
655655
except UnicodeError:
656-
raise InvalidStringData("strings in documents must be valid UTF-8: %r" % string)
656+
raise InvalidStringData(
657+
"strings in documents must be valid UTF-8: %r" % string
658+
) from None
657659
else:
658660
if "\x00" in string:
659661
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
@@ -667,7 +669,9 @@ def _make_c_string(string: Union[str, bytes]) -> bytes:
667669
_utf_8_decode(string, None, True)
668670
return string + b"\x00"
669671
except UnicodeError:
670-
raise InvalidStringData("strings in documents must be valid UTF-8: %r" % string)
672+
raise InvalidStringData(
673+
"strings in documents must be valid UTF-8: %r" % string
674+
) from None
671675
else:
672676
return _utf_8_encode(string)[0] + b"\x00"
673677

@@ -817,7 +821,7 @@ def _encode_int(name: bytes, value: int, dummy0: Any, dummy1: Any) -> bytes:
817821
try:
818822
return b"\x12" + name + _PACK_LONG(value)
819823
except struct.error:
820-
raise OverflowError("BSON can only handle up to 8-byte ints")
824+
raise OverflowError("BSON can only handle up to 8-byte ints") from None
821825

822826

823827
def _encode_timestamp(name: bytes, value: Any, dummy0: Any, dummy1: Any) -> bytes:
@@ -830,7 +834,7 @@ def _encode_long(name: bytes, value: Any, dummy0: Any, dummy1: Any) -> bytes:
830834
try:
831835
return b"\x12" + name + _PACK_LONG(value)
832836
except struct.error:
833-
raise OverflowError("BSON can only handle up to 8-byte ints")
837+
raise OverflowError("BSON can only handle up to 8-byte ints") from None
834838

835839

836840
def _encode_decimal128(name: bytes, value: Decimal128, dummy0: Any, dummy1: Any) -> bytes:
@@ -995,14 +999,14 @@ def _dict_to_bson(
995999
if not top_level or key != "_id":
9961000
elements.append(_element_to_bson(key, value, check_keys, opts))
9971001
except AttributeError:
998-
raise TypeError(f"encoder expected a mapping type but got: {doc!r}")
1002+
raise TypeError(f"encoder expected a mapping type but got: {doc!r}") from None
9991003

10001004
encoded = b"".join(elements)
10011005
return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
10021006

10031007

10041008
if _USE_C:
1005-
_dict_to_bson = _cbson._dict_to_bson # noqa: F811
1009+
_dict_to_bson = _cbson._dict_to_bson
10061010

10071011

10081012
_CODEC_OPTIONS_TYPE_ERROR = TypeError("codec_options must be an instance of CodecOptions")
@@ -1110,11 +1114,11 @@ def _decode_all(data: _ReadableBuffer, opts: CodecOptions[_DocumentType]) -> lis
11101114
except Exception:
11111115
# Change exception type to InvalidBSON but preserve traceback.
11121116
_, exc_value, exc_tb = sys.exc_info()
1113-
raise InvalidBSON(str(exc_value)).with_traceback(exc_tb)
1117+
raise InvalidBSON(str(exc_value)).with_traceback(exc_tb) from None
11141118

11151119

11161120
if _USE_C:
1117-
_decode_all = _cbson._decode_all # noqa: F811
1121+
_decode_all = _cbson._decode_all
11181122

11191123

11201124
@overload
@@ -1207,7 +1211,7 @@ def _array_of_documents_to_buffer(view: memoryview) -> bytes:
12071211

12081212

12091213
if _USE_C:
1210-
_array_of_documents_to_buffer = _cbson._array_of_documents_to_buffer # noqa: F811
1214+
_array_of_documents_to_buffer = _cbson._array_of_documents_to_buffer
12111215

12121216

12131217
def _convert_raw_document_lists_to_streams(document: Any) -> None:

bson/binary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def __new__(
242242
@classmethod
243243
def from_uuid(
244244
cls: Type[Binary], uuid: UUID, uuid_representation: int = UuidRepresentation.STANDARD
245-
) -> "Binary":
245+
) -> Binary:
246246
"""Create a BSON Binary object from a Python UUID.
247247
248248
Creates a :class:`~bson.binary.Binary` object from a

bson/codec_options.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
168168
if issubclass(cast(TypeCodec, codec).python_type, pytype):
169169
err_msg = (
170170
"TypeEncoders cannot change how built-in types are "
171-
"encoded (encoder {} transforms type {})".format(codec, pytype)
171+
f"encoded (encoder {codec} transforms type {pytype})"
172172
)
173173
raise TypeError(err_msg)
174174

bson/datetime_ms.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@ def __hash__(self) -> int:
7575
def __repr__(self) -> str:
7676
return type(self).__name__ + "(" + str(self._value) + ")"
7777

78-
def __lt__(self, other: Union["DatetimeMS", int]) -> bool:
78+
def __lt__(self, other: Union[DatetimeMS, int]) -> bool:
7979
return self._value < other
8080

81-
def __le__(self, other: Union["DatetimeMS", int]) -> bool:
81+
def __le__(self, other: Union[DatetimeMS, int]) -> bool:
8282
return self._value <= other
8383

8484
def __eq__(self, other: Any) -> bool:
@@ -91,10 +91,10 @@ def __ne__(self, other: Any) -> bool:
9191
return self._value != other._value
9292
return True
9393

94-
def __gt__(self, other: Union["DatetimeMS", int]) -> bool:
94+
def __gt__(self, other: Union[DatetimeMS, int]) -> bool:
9595
return self._value > other
9696

97-
def __ge__(self, other: Union["DatetimeMS", int]) -> bool:
97+
def __ge__(self, other: Union[DatetimeMS, int]) -> bool:
9898
return self._value >= other
9999

100100
_type_marker = 9

bson/dbref.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def __getattr__(self, key: Any) -> Any:
8989
try:
9090
return self.__kwargs[key]
9191
except KeyError:
92-
raise AttributeError(key)
92+
raise AttributeError(key) from None
9393

9494
def as_doc(self) -> SON[str, Any]:
9595
"""Get the SON document representation of this DBRef.

bson/decimal128.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def __str__(self) -> str:
298298
return str(dec)
299299

300300
def __repr__(self) -> str:
301-
return f"Decimal128('{str(self)}')"
301+
return f"Decimal128('{self!s}')"
302302

303303
def __setstate__(self, value: Tuple[int, int]) -> None:
304304
self.__high, self.__low = value

bson/errors.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
"""Exceptions raised by the BSON package."""
16+
from __future__ import annotations
1617

1718

1819
class BSONError(Exception):

bson/json_util.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -737,8 +737,7 @@ def _parse_canonical_regex(doc: Any) -> Regex[str]:
737737
raise TypeError(f"Bad $regularExpression, extra field(s): {doc}")
738738
if len(regex) != 2:
739739
raise TypeError(
740-
'Bad $regularExpression must include only "pattern"'
741-
'and "options" components: {}'.format(doc)
740+
f'Bad $regularExpression must include only "pattern and "options" components: {doc}'
742741
)
743742
opts = regex["options"]
744743
if not isinstance(opts, str):
@@ -812,7 +811,7 @@ def _parse_canonical_decimal128(doc: Any) -> Decimal128:
812811

813812
def _parse_canonical_minkey(doc: Any) -> MinKey:
814813
"""Decode a JSON MinKey to bson.min_key.MinKey."""
815-
if type(doc["$minKey"]) is not int or doc["$minKey"] != 1:
814+
if type(doc["$minKey"]) is not int or doc["$minKey"] != 1: # noqa: E721
816815
raise TypeError(f"$minKey value must be 1: {doc}")
817816
if len(doc) != 1:
818817
raise TypeError(f"Bad $minKey, extra field(s): {doc}")
@@ -821,7 +820,7 @@ def _parse_canonical_minkey(doc: Any) -> MinKey:
821820

822821
def _parse_canonical_maxkey(doc: Any) -> MaxKey:
823822
"""Decode a JSON MaxKey to bson.max_key.MaxKey."""
824-
if type(doc["$maxKey"]) is not int or doc["$maxKey"] != 1:
823+
if type(doc["$maxKey"]) is not int or doc["$maxKey"] != 1: # noqa: E721
825824
raise TypeError("$maxKey value must be 1: %s", (doc,))
826825
if len(doc) != 1:
827826
raise TypeError(f"Bad $minKey, extra field(s): {doc}")

0 commit comments

Comments
 (0)