Skip to content

Commit f16f6d5

Browse files
committed
PYTHON-2504 ruff --fix-only --select ALL --fixable ALL --target-version py37 --line-length=100 --unfixable COM812,D400,D415,ERA001,RUF100,SIM108,D211,D212,SIM105,SIM,PT,ANN204 bson/*.py pymongo/*.py gridfs/*.py test/*.py test/*/*.py
1 parent 7e6081a commit f16f6d5

File tree

114 files changed

+1391
-1112
lines changed

Some content is hidden

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

114 files changed

+1391
-1112
lines changed

bson/__init__.py

Lines changed: 54 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -236,10 +236,8 @@ def get_data_and_view(data: Any) -> Tuple[Any, memoryview]:
236236

237237
def _raise_unknown_type(element_type: int, element_name: str) -> NoReturn:
238238
"""Unknown type helper."""
239-
raise InvalidBSON(
240-
"Detected unknown BSON type %r for fieldname '%s'. Are "
241-
"you using the latest driver version?" % (chr(element_type).encode(), element_name)
242-
)
239+
msg = f"Detected unknown BSON type {chr(element_type).encode()!r} for fieldname '{element_name}'. Are you using the latest driver version?"
240+
raise InvalidBSON(msg)
243241

244242

245243
def _get_int(
@@ -269,10 +267,12 @@ def _get_string(
269267
length = _UNPACK_INT_FROM(data, position)[0]
270268
position += 4
271269
if length < 1 or obj_end - position < length:
272-
raise InvalidBSON("invalid string length")
270+
msg = "invalid string length"
271+
raise InvalidBSON(msg)
273272
end = position + length - 1
274273
if data[end] != 0:
275-
raise InvalidBSON("invalid end of string")
274+
msg = "invalid end of string"
275+
raise InvalidBSON(msg)
276276
return _utf_8_decode(view[position:end], opts.unicode_decode_error_handler, True)[0], end + 1
277277

278278

@@ -284,12 +284,15 @@ def _get_object_size(data: Any, position: int, obj_end: int) -> Tuple[int, int]:
284284
raise InvalidBSON(str(exc))
285285
end = position + obj_size - 1
286286
if data[end] != 0:
287-
raise InvalidBSON("bad eoo")
287+
msg = "bad eoo"
288+
raise InvalidBSON(msg)
288289
if end >= obj_end:
289-
raise InvalidBSON("invalid object length")
290+
msg = "invalid object length"
291+
raise InvalidBSON(msg)
290292
# If this is the top-level document, validate the total size too.
291293
if position == 0 and obj_size != obj_end:
292-
raise InvalidBSON("invalid object length")
294+
msg = "invalid object length"
295+
raise InvalidBSON(msg)
293296
return obj_size, end
294297

295298

@@ -321,7 +324,8 @@ def _get_array(
321324
size = _UNPACK_INT_FROM(data, position)[0]
322325
end = position + size - 1
323326
if data[end] != 0:
324-
raise InvalidBSON("bad eoo")
327+
msg = "bad eoo"
328+
raise InvalidBSON(msg)
325329

326330
position += 4
327331
end -= 1
@@ -352,7 +356,8 @@ def _get_array(
352356
append(value)
353357

354358
if position != end + 1:
355-
raise InvalidBSON("bad array length")
359+
msg = "bad array length"
360+
raise InvalidBSON(msg)
356361
return result, position + 1
357362

358363

@@ -366,11 +371,13 @@ def _get_binary(
366371
length2 = _UNPACK_INT_FROM(data, position)[0]
367372
position += 4
368373
if length2 != length - 4:
369-
raise InvalidBSON("invalid binary (st 2) - lengths don't match!")
374+
msg = "invalid binary (st 2) - lengths don't match!"
375+
raise InvalidBSON(msg)
370376
length = length2
371377
end = position + length
372378
if length < 0 or end > obj_end:
373-
raise InvalidBSON("bad binary object length")
379+
msg = "bad binary object length"
380+
raise InvalidBSON(msg)
374381

375382
# Convert UUID subtypes to native UUIDs.
376383
if subtype in ALL_UUID_SUBTYPES:
@@ -437,7 +444,8 @@ def _get_code_w_scope(
437444
code, position = _get_string(data, view, position + 4, code_end, opts, element_name)
438445
scope, position = _get_object(data, view, position, code_end, opts, element_name)
439446
if position != code_end:
440-
raise InvalidBSON("scope outside of javascript code boundaries")
447+
msg = "scope outside of javascript code boundaries"
448+
raise InvalidBSON(msg)
441449
return Code(code, scope), position
442450

443451

@@ -587,7 +595,8 @@ def _elements_to_dict(
587595
)
588596
result[key] = value
589597
if position != obj_end:
590-
raise InvalidBSON("bad object or element length")
598+
msg = "bad object or element length"
599+
raise InvalidBSON(msg)
591600
return result
592601

593602

@@ -637,15 +646,17 @@ def _make_c_string_check(string: Union[str, bytes]) -> bytes:
637646
"""Make a 'C' string, checking for embedded NUL characters."""
638647
if isinstance(string, bytes):
639648
if b"\x00" in string:
640-
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
649+
msg = "BSON keys / regex patterns must not contain a NUL character"
650+
raise InvalidDocument(msg)
641651
try:
642652
_utf_8_decode(string, None, True)
643653
return string + b"\x00"
644654
except UnicodeError:
645655
raise InvalidStringData("strings in documents must be valid UTF-8: %r" % string)
646656
else:
647657
if "\x00" in string:
648-
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
658+
msg = "BSON keys / regex patterns must not contain a NUL character"
659+
raise InvalidDocument(msg)
649660
return _utf_8_encode(string)[0] + b"\x00"
650661

651662

@@ -665,7 +676,8 @@ def _make_name(string: str) -> bytes:
665676
"""Make a 'C' string suitable for a BSON key."""
666677
# Keys can only be text in python 3.
667678
if "\x00" in string:
668-
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
679+
msg = "BSON keys / regex patterns must not contain a NUL character"
680+
raise InvalidDocument(msg)
669681
return _utf_8_encode(string)[0] + b"\x00"
670682

671683

@@ -805,7 +817,8 @@ def _encode_int(name: bytes, value: int, dummy0: Any, dummy1: Any) -> bytes:
805817
try:
806818
return b"\x12" + name + _PACK_LONG(value)
807819
except struct.error:
808-
raise OverflowError("BSON can only handle up to 8-byte ints")
820+
msg = "BSON can only handle up to 8-byte ints"
821+
raise OverflowError(msg)
809822

810823

811824
def _encode_timestamp(name: bytes, value: Any, dummy0: Any, dummy1: Any) -> bytes:
@@ -818,7 +831,8 @@ def _encode_long(name: bytes, value: Any, dummy0: Any, dummy1: Any) -> bytes:
818831
try:
819832
return b"\x12" + name + _PACK_LONG(value)
820833
except struct.error:
821-
raise OverflowError("BSON can only handle up to 8-byte ints")
834+
msg = "BSON can only handle up to 8-byte ints"
835+
raise OverflowError(msg)
822836

823837

824838
def _encode_decimal128(name: bytes, value: Decimal128, dummy0: Any, dummy1: Any) -> bytes:
@@ -941,18 +955,22 @@ def _name_value_to_bson(
941955
name, fallback_encoder(value), check_keys, opts, in_fallback_call=True
942956
)
943957

944-
raise InvalidDocument(f"cannot encode object: {value!r}, of type: {type(value)!r}")
958+
msg = f"cannot encode object: {value!r}, of type: {type(value)!r}"
959+
raise InvalidDocument(msg)
945960

946961

947962
def _element_to_bson(key: Any, value: Any, check_keys: bool, opts: CodecOptions) -> bytes:
948963
"""Encode a single key, value pair."""
949964
if not isinstance(key, str):
950-
raise InvalidDocument(f"documents must have only string keys, key was {key!r}")
965+
msg = f"documents must have only string keys, key was {key!r}"
966+
raise InvalidDocument(msg)
951967
if check_keys:
952968
if key.startswith("$"):
953-
raise InvalidDocument(f"key {key!r} must not start with '$'")
969+
msg = f"key {key!r} must not start with '$'"
970+
raise InvalidDocument(msg)
954971
if "." in key:
955-
raise InvalidDocument(f"key {key!r} must not contain '.'")
972+
msg = f"key {key!r} must not contain '.'"
973+
raise InvalidDocument(msg)
956974

957975
name = _make_name(key)
958976
return _name_value_to_bson(name, value, check_keys, opts)
@@ -970,7 +988,8 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: CodecOptions, top_level: boo
970988
if not top_level or key != "_id":
971989
elements.append(_element_to_bson(key, value, check_keys, opts))
972990
except AttributeError:
973-
raise TypeError(f"encoder expected a mapping type but got: {doc!r}")
991+
msg = f"encoder expected a mapping type but got: {doc!r}"
992+
raise TypeError(msg)
974993

975994
encoded = b"".join(elements)
976995
return _PACK_INT(len(encoded) + 5) + encoded + b"\x00"
@@ -1063,10 +1082,12 @@ def _decode_all(
10631082
while position < end:
10641083
obj_size = _UNPACK_INT_FROM(data, position)[0]
10651084
if data_len - position < obj_size:
1066-
raise InvalidBSON("invalid object size")
1085+
msg = "invalid object size"
1086+
raise InvalidBSON(msg)
10671087
obj_end = position + obj_size - 1
10681088
if data[obj_end] != 0:
1069-
raise InvalidBSON("bad eoo")
1089+
msg = "bad eoo"
1090+
raise InvalidBSON(msg)
10701091
if use_raw:
10711092
docs.append(opts.document_class(data[position : obj_end + 1], opts)) # type: ignore
10721093
else:
@@ -1152,7 +1173,8 @@ def _array_of_documents_to_buffer(view: memoryview) -> bytes:
11521173
append(view[position : position + obj_size])
11531174
position += obj_size
11541175
if position != end:
1155-
raise InvalidBSON("bad object or element length")
1176+
msg = "bad object or element length"
1177+
raise InvalidBSON(msg)
11561178
return b"".join(buffers)
11571179

11581180

@@ -1283,7 +1305,8 @@ def decode_file_iter(
12831305
if not size_data:
12841306
break # Finished with file normally.
12851307
elif len(size_data) != 4:
1286-
raise InvalidBSON("cut off in middle of objsize")
1308+
msg = "cut off in middle of objsize"
1309+
raise InvalidBSON(msg)
12871310
obj_size = _UNPACK_INT_FROM(size_data, 0)[0] - 4
12881311
elements = size_data + file_obj.read(max(0, obj_size))
12891312
yield _bson_to_dict(elements, opts)
@@ -1300,7 +1323,8 @@ def is_valid(bson: bytes) -> bool:
13001323
- `bson`: the data to be validated
13011324
"""
13021325
if not isinstance(bson, bytes):
1303-
raise TypeError("BSON data must be an instance of a subclass of bytes")
1326+
msg = "BSON data must be an instance of a subclass of bytes"
1327+
raise TypeError(msg)
13041328

13051329
try:
13061330
_bson_to_dict(bson, DEFAULT_CODEC_OPTIONS)

bson/_helpers.py

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

1515
"""Setstate and getstate functions for objects with __slots__, allowing
16-
compatibility with default pickling protocol
16+
compatibility with default pickling protocol
1717
"""
1818
from typing import Any, Mapping
1919

@@ -33,7 +33,7 @@ def _mangle_name(name: str, prefix: str) -> str:
3333

3434
def _getstate_slots(self: Any) -> Mapping[Any, Any]:
3535
prefix = self.__class__.__name__
36-
ret = dict()
36+
ret = {}
3737
for name in self.__slots__:
3838
mangled_name = _mangle_name(name, prefix)
3939
if hasattr(self, mangled_name):

bson/binary.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -224,9 +224,11 @@ def __new__(
224224
subtype: int = BINARY_SUBTYPE,
225225
) -> "Binary":
226226
if not isinstance(subtype, int):
227-
raise TypeError("subtype must be an instance of int")
227+
msg = "subtype must be an instance of int"
228+
raise TypeError(msg)
228229
if subtype >= 256 or subtype < 0:
229-
raise ValueError("subtype must be contained in [0, 256)")
230+
msg = "subtype must be contained in [0, 256)"
231+
raise ValueError(msg)
230232
# Support any type that implements the buffer protocol.
231233
self = bytes.__new__(cls, memoryview(data).tobytes())
232234
self.__subtype = subtype
@@ -256,22 +258,16 @@ def from_uuid(
256258
.. versionadded:: 3.11
257259
"""
258260
if not isinstance(uuid, UUID):
259-
raise TypeError("uuid must be an instance of uuid.UUID")
261+
msg = "uuid must be an instance of uuid.UUID"
262+
raise TypeError(msg)
260263

261264
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
262-
raise ValueError(
263-
"uuid_representation must be a value from bson.binary.UuidRepresentation"
264-
)
265+
msg = "uuid_representation must be a value from bson.binary.UuidRepresentation"
266+
raise ValueError(msg)
265267

266268
if uuid_representation == UuidRepresentation.UNSPECIFIED:
267-
raise ValueError(
268-
"cannot encode native uuid.UUID with "
269-
"UuidRepresentation.UNSPECIFIED. UUIDs can be manually "
270-
"converted to bson.Binary instances using "
271-
"bson.Binary.from_uuid() or a different UuidRepresentation "
272-
"can be configured. See the documentation for "
273-
"UuidRepresentation for more information."
274-
)
269+
msg = "cannot encode native uuid.UUID with UuidRepresentation.UNSPECIFIED. UUIDs can be manually converted to bson.Binary instances using bson.Binary.from_uuid() or a different UuidRepresentation can be configured. See the documentation for UuidRepresentation for more information."
270+
raise ValueError(msg)
275271

276272
subtype = OLD_UUID_SUBTYPE
277273
if uuid_representation == UuidRepresentation.PYTHON_LEGACY:
@@ -306,15 +302,16 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
306302
.. versionadded:: 3.11
307303
"""
308304
if self.subtype not in ALL_UUID_SUBTYPES:
309-
raise ValueError(f"cannot decode subtype {self.subtype} as a uuid")
305+
msg = f"cannot decode subtype {self.subtype} as a uuid"
306+
raise ValueError(msg)
310307

311308
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
312-
raise ValueError(
313-
"uuid_representation must be a value from bson.binary.UuidRepresentation"
314-
)
309+
msg = "uuid_representation must be a value from bson.binary.UuidRepresentation"
310+
raise ValueError(msg)
315311

316312
if uuid_representation == UuidRepresentation.UNSPECIFIED:
317-
raise ValueError("uuid_representation cannot be UNSPECIFIED")
313+
msg = "uuid_representation cannot be UNSPECIFIED"
314+
raise ValueError(msg)
318315
elif uuid_representation == UuidRepresentation.PYTHON_LEGACY:
319316
if self.subtype == OLD_UUID_SUBTYPE:
320317
return UUID(bytes=self)
@@ -330,8 +327,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
330327
return UUID(bytes=self)
331328

332329
raise ValueError(
333-
"cannot decode subtype %s to %s"
334-
% (self.subtype, UUID_REPRESENTATION_NAMES[uuid_representation])
330+
f"cannot decode subtype {self.subtype} to {UUID_REPRESENTATION_NAMES[uuid_representation]}"
335331
)
336332

337333
@property

bson/code.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tools for representing JavaScript code in BSON.
16-
"""
15+
"""Tools for representing JavaScript code in BSON."""
1716

1817
from collections.abc import Mapping as _Mapping
1918
from typing import Any, Mapping, Optional, Type, Union
@@ -57,7 +56,8 @@ def __new__(
5756
**kwargs: Any,
5857
) -> "Code":
5958
if not isinstance(code, str):
60-
raise TypeError("code must be an instance of str")
59+
msg = "code must be an instance of str"
60+
raise TypeError(msg)
6161

6262
self = str.__new__(cls, code)
6363

@@ -68,7 +68,8 @@ def __new__(
6868

6969
if scope is not None:
7070
if not isinstance(scope, _Mapping):
71-
raise TypeError("scope must be an instance of dict")
71+
msg = "scope must be an instance of dict"
72+
raise TypeError(msg)
7273
if self.__scope is not None:
7374
self.__scope.update(scope) # type: ignore
7475
else:

0 commit comments

Comments
 (0)