Skip to content

Commit 713d0a9

Browse files
committed
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,EM bson/*.py pymongo/*.py gridfs/*.py test/*.py test/*/*.py
1 parent 7e6081a commit 713d0a9

Some content is hidden

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

89 files changed

+462
-422
lines changed

bson/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,8 +237,8 @@ def get_data_and_view(data: Any) -> Tuple[Any, memoryview]:
237237
def _raise_unknown_type(element_type: int, element_name: str) -> NoReturn:
238238
"""Unknown type helper."""
239239
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)
240+
"Detected unknown BSON type {!r} for fieldname '{}'. Are "
241+
"you using the latest driver version?".format(chr(element_type).encode(), element_name)
242242
)
243243

244244

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: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -330,8 +330,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
330330
return UUID(bytes=self)
331331

332332
raise ValueError(
333-
"cannot decode subtype %s to %s"
334-
% (self.subtype, UUID_REPRESENTATION_NAMES[uuid_representation])
333+
f"cannot decode subtype {self.subtype} to {UUID_REPRESENTATION_NAMES[uuid_representation]}"
335334
)
336335

337336
@property

bson/code.py

Lines changed: 1 addition & 2 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

bson/codec_options.py

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,10 @@ class TypeEncoder(abc.ABC):
6363
@abc.abstractproperty
6464
def python_type(self) -> Any:
6565
"""The Python type to be converted into something serializable."""
66-
pass
6766

6867
@abc.abstractmethod
6968
def transform_python(self, value: Any) -> Any:
7069
"""Convert the given Python object into something serializable."""
71-
pass
7270

7371

7472
class TypeDecoder(abc.ABC):
@@ -84,12 +82,10 @@ class TypeDecoder(abc.ABC):
8482
@abc.abstractproperty
8583
def bson_type(self) -> Any:
8684
"""The BSON type to be converted into our own type."""
87-
pass
8885

8986
@abc.abstractmethod
9087
def transform_bson(self, value: Any) -> Any:
9188
"""Convert the given BSON value into our own type."""
92-
pass
9389

9490

9591
class TypeCodec(TypeEncoder, TypeDecoder):
@@ -105,8 +101,6 @@ class TypeCodec(TypeEncoder, TypeDecoder):
105101
See :ref:`custom-type-type-codec` documentation for an example.
106102
"""
107103

108-
pass
109-
110104

111105
_Codec = Union[TypeEncoder, TypeDecoder, TypeCodec]
112106
_Fallback = Callable[[Any], Any]
@@ -164,8 +158,7 @@ def __init__(
164158
self._decoder_map[codec.bson_type] = codec.transform_bson
165159
if not is_valid_codec:
166160
raise TypeError(
167-
"Expected an instance of %s, %s, or %s, got %r instead"
168-
% (TypeEncoder.__name__, TypeDecoder.__name__, TypeCodec.__name__, codec)
161+
f"Expected an instance of {TypeEncoder.__name__}, {TypeDecoder.__name__}, or {TypeCodec.__name__}, got {codec!r} instead"
169162
)
170163

171164
def _validate_type_encoder(self, codec: _Codec) -> None:
@@ -175,7 +168,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None:
175168
if issubclass(cast(TypeCodec, codec).python_type, pytype):
176169
err_msg = (
177170
"TypeEncoders cannot change how built-in types are "
178-
"encoded (encoder %s transforms type %s)" % (codec, pytype)
171+
"encoded (encoder {} transforms type {})".format(codec, pytype)
179172
)
180173
raise TypeError(err_msg)
181174

@@ -446,10 +439,9 @@ def _arguments_repr(self) -> str:
446439
)
447440

448441
return (
449-
"document_class=%s, tz_aware=%r, uuid_representation=%s, "
450-
"unicode_decode_error_handler=%r, tzinfo=%r, "
451-
"type_registry=%r, datetime_conversion=%s"
452-
% (
442+
"document_class={}, tz_aware={!r}, uuid_representation={}, "
443+
"unicode_decode_error_handler={!r}, tzinfo={!r}, "
444+
"type_registry={!r}, datetime_conversion={}".format(
453445
document_class_repr,
454446
self.tz_aware,
455447
uuid_rep_repr,

bson/json_util.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -350,10 +350,9 @@ def __new__(
350350

351351
def _arguments_repr(self) -> str:
352352
return (
353-
"strict_number_long=%r, "
354-
"datetime_representation=%r, "
355-
"strict_uuid=%r, json_mode=%r, %s"
356-
% (
353+
"strict_number_long={!r}, "
354+
"datetime_representation={!r}, "
355+
"strict_uuid={!r}, json_mode={!r}, {}".format(
357356
self.strict_number_long,
358357
self.datetime_representation,
359358
self.strict_uuid,
@@ -492,7 +491,7 @@ def _json_convert(obj: Any, json_options: JSONOptions = DEFAULT_JSON_OPTIONS) ->
492491
if hasattr(obj, "items"):
493492
return SON(((k, _json_convert(v, json_options)) for k, v in obj.items()))
494493
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes)):
495-
return list(_json_convert(v, json_options) for v in obj)
494+
return [_json_convert(v, json_options) for v in obj]
496495
try:
497496
return default(obj, json_options)
498497
except TypeError:
@@ -720,7 +719,7 @@ def _parse_canonical_regex(doc: Any) -> Regex:
720719
if len(regex) != 2:
721720
raise TypeError(
722721
'Bad $regularExpression must include only "pattern"'
723-
'and "options" components: %s' % (doc,)
722+
'and "options" components: {}'.format(doc)
724723
)
725724
opts = regex["options"]
726725
if not isinstance(opts, str):

bson/max_key.py

Lines changed: 1 addition & 2 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-
"""Representation for the MongoDB internal MaxKey type.
16-
"""
15+
"""Representation for the MongoDB internal MaxKey type."""
1716
from typing import Any
1817

1918

bson/min_key.py

Lines changed: 1 addition & 2 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-
"""Representation for the MongoDB internal MinKey type.
16-
"""
15+
"""Representation for the MongoDB internal MinKey type."""
1716
from typing import Any
1817

1918

bson/objectid.py

Lines changed: 3 additions & 5 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 working with MongoDB ObjectIds.
16-
"""
15+
"""Tools for working with MongoDB ObjectIds."""
1716

1817
import binascii
1918
import calendar
@@ -166,7 +165,6 @@ def _random(cls) -> bytes:
166165

167166
def __generate(self) -> None:
168167
"""Generate a new value for this ObjectId."""
169-
170168
# 4 bytes current time
171169
oid = struct.pack(">I", int(time.time()))
172170

@@ -222,13 +220,13 @@ def generation_time(self) -> datetime.datetime:
222220
return datetime.datetime.fromtimestamp(timestamp, utc)
223221

224222
def __getstate__(self) -> bytes:
225-
"""return value of object for pickling.
223+
"""Return value of object for pickling.
226224
needed explicitly because __slots__() defined.
227225
"""
228226
return self.__id
229227

230228
def __setstate__(self, value: Any) -> None:
231-
"""explicit state set from pickling"""
229+
"""Explicit state set from pickling"""
232230
# Provide backwards compatibility with OIDs
233231
# pickled with pymongo-1.9 or older.
234232
if isinstance(value, dict):

bson/raw_bson.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ class from the standard library so it can be used like a read-only
131131
elif not issubclass(codec_options.document_class, RawBSONDocument):
132132
raise TypeError(
133133
"RawBSONDocument cannot use CodecOptions with document "
134-
"class %s" % (codec_options.document_class,)
134+
"class {}".format(codec_options.document_class)
135135
)
136136
self.__codec_options = codec_options
137137
# Validate the bson object size.

bson/regex.py

Lines changed: 1 addition & 2 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 MongoDB regular expressions.
16-
"""
15+
"""Tools for representing MongoDB regular expressions."""
1716

1817
import re
1918
from typing import Any, Generic, Pattern, Type, TypeVar, Union

bson/son.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
1717
Regular dictionaries can be used instead of SON objects, but not when the order
1818
of keys is important. A SON object can be used just like a normal Python
19-
dictionary."""
19+
dictionary.
20+
"""
2021

2122
import copy
2223
import re

bson/timestamp.py

Lines changed: 1 addition & 2 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 MongoDB internal Timestamps.
16-
"""
15+
"""Tools for representing MongoDB internal Timestamps."""
1716

1817
import calendar
1918
import datetime

gridfs/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,6 @@ def put(self, data: Any, **kwargs: Any) -> Any:
141141
.. versionchanged:: 3.0
142142
w=0 writes to GridFS are now prohibited.
143143
"""
144-
145144
with GridIn(self.__collection, **kwargs) as grid_file:
146145
grid_file.write(data)
147146
return grid_file._id

pymongo/auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ def speculate_command(self):
569569
authenticator = _get_authenticator(self.credentials, self.address)
570570
cmd = authenticator.auth_start_cmd(False)
571571
if cmd is None:
572-
return
572+
return None
573573
cmd["db"] = self.credentials.source
574574
return cmd
575575

pymongo/auth_oidc.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,11 @@ def get_current_token(self, use_callbacks=True):
131131

132132
refresh_token = self.idp_resp and self.idp_resp.get("refresh_token")
133133
refresh_token = refresh_token or ""
134-
context = dict(
135-
timeout_seconds=timeout,
136-
version=CALLBACK_VERSION,
137-
refresh_token=refresh_token,
138-
)
134+
context = {
135+
"timeout_seconds": timeout,
136+
"version": CALLBACK_VERSION,
137+
"refresh_token": refresh_token,
138+
}
139139

140140
if self.idp_resp is None or refresh_cb is None:
141141
self.idp_resp = request_cb(self.idp_info, context)
@@ -181,7 +181,7 @@ def auth_start_cmd(self, use_callbacks=True):
181181
aws_identity_file = os.environ["AWS_WEB_IDENTITY_TOKEN_FILE"]
182182
with open(aws_identity_file) as fid:
183183
token = fid.read().strip()
184-
payload = dict(jwt=token)
184+
payload = {"jwt": token}
185185
cmd = SON(
186186
[
187187
("saslStart", 1),
@@ -203,7 +203,7 @@ def auth_start_cmd(self, use_callbacks=True):
203203

204204
if self.idp_info is None:
205205
# Send the SASL start with the optional principal name.
206-
payload = dict()
206+
payload = {}
207207

208208
if principal_name:
209209
payload["n"] = principal_name
@@ -221,7 +221,7 @@ def auth_start_cmd(self, use_callbacks=True):
221221
token = self.get_current_token(use_callbacks)
222222
if not token:
223223
return None
224-
bin_payload = Binary(bson.encode(dict(jwt=token)))
224+
bin_payload = Binary(bson.encode({"jwt": token}))
225225
return SON(
226226
[
227227
("saslStart", 1),
@@ -268,7 +268,7 @@ def authenticate(self, sock_info, reauthenticate=False):
268268

269269
if resp["done"]:
270270
sock_info.oidc_token_gen_id = self.token_gen_id
271-
return
271+
return None
272272

273273
server_resp: Dict = bson.decode(resp["payload"])
274274
if "issuer" in server_resp:
@@ -278,7 +278,7 @@ def authenticate(self, sock_info, reauthenticate=False):
278278
conversation_id = resp["conversationId"]
279279
token = self.get_current_token()
280280
sock_info.oidc_token_gen_id = self.token_gen_id
281-
bin_payload = Binary(bson.encode(dict(jwt=token)))
281+
bin_payload = Binary(bson.encode({"jwt": token}))
282282
cmd = SON(
283283
[
284284
("saslContinue", 1),

pymongo/bulk.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,5 +509,6 @@ def execute(self, write_concern, session):
509509
if not write_concern.acknowledged:
510510
with client._socket_for_writes(session) as sock_info:
511511
self.execute_no_results(sock_info, generator, write_concern)
512+
return None
512513
else:
513514
return self.execute_command(generator, write_concern, session)

pymongo/change_stream.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ def _aggregation_command_class(self):
156156
@property
157157
def _client(self):
158158
"""The client against which the aggregation commands for
159-
this ChangeStream will be run."""
159+
this ChangeStream will be run.
160+
"""
160161
raise NotImplementedError
161162

162163
def _change_stream_options(self):
@@ -221,7 +222,7 @@ def _process_result(self, result, sock_info):
221222
if self._start_at_operation_time is None:
222223
raise OperationFailure(
223224
"Expected field 'operationTime' missing from command "
224-
"response : %r" % (result,)
225+
"response : {!r}".format(result)
225226
)
226227

227228
def _run_aggregation_cmd(self, session, explicit_session):

0 commit comments

Comments
 (0)