Skip to content

Commit a0fe7c0

Browse files
authored
PYTHON-3120 Set up flake8 linting (mongodb#868)
1 parent 1a90e47 commit a0fe7c0

File tree

105 files changed

+454
-535
lines changed

Some content is hidden

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

105 files changed

+454
-535
lines changed

.flake8

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
[flake8]
2+
max-line-length = 100
3+
enable-extensions = G
4+
extend-ignore =
5+
G200, G202,
6+
# black adds spaces around ':'
7+
E203,
8+
# E501 line too long (let black handle line length)
9+
E501
10+
# B305 `.next()` is not a thing on Python 3
11+
B305
12+
per-file-ignores =
13+
# E402 module level import not at top of file
14+
pymongo/__init__.py: E402
15+
16+
# G004 Logging statement uses f-string
17+
pymongo/event_loggers.py: G004
18+
19+
# E402 module level import not at top of file
20+
# B011 Do not call assert False since python -O removes these calls
21+
# F405 'Foo' may be undefined, or defined from star imports
22+
# E741 ambiguous variable name
23+
# B007 Loop control variable 'foo' not used within the loop body
24+
# F403 'from foo import *' used; unable to detect undefined names
25+
# B001 Do not use bare `except:`
26+
# E722 do not use bare 'except'
27+
# E731 do not assign a lambda expression, use a def
28+
# F811 redefinition of unused 'foo' from line XXX
29+
# F841 local variable 'foo' is assigned to but never used
30+
test/*: E402, B011, F405, E741, B007, F403, B001, E722, E731, F811, F841

.github/workflows/test-python.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ jobs:
3131
uses: actions/setup-python@v2
3232
with:
3333
python-version: ${{ matrix.python-version }}
34+
cache: 'pip'
35+
cache-dependency-path: 'setup.py'
3436
- name: Start MongoDB
3537
uses: supercharge/[email protected]
3638
with:
@@ -53,6 +55,8 @@ jobs:
5355
uses: actions/setup-python@v2
5456
with:
5557
python-version: ${{ matrix.python-version }}
58+
cache: 'pip'
59+
cache-dependency-path: 'setup.py'
5660
- name: Install dependencies
5761
run: |
5862
python -m pip install -U pip mypy

.pre-commit-config.yaml

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
repos:
33
- repo: https://github.com/pre-commit/pre-commit-hooks
4-
rev: v3.4.0
4+
rev: v4.1.0
55
hooks:
66
- id: check-added-large-files
77
- id: check-case-conflict
@@ -24,17 +24,36 @@ repos:
2424
args: [--line-length=100]
2525

2626
- repo: https://github.com/PyCQA/isort
27-
rev: 5.7.0
27+
rev: 5.10.1
2828
hooks:
2929
- id: isort
3030
files: \.py$
3131
args: [--profile=black]
3232

33+
- repo: https://gitlab.com/pycqa/flake8
34+
rev: 3.9.2
35+
hooks:
36+
- id: flake8
37+
additional_dependencies: [
38+
'flake8-bugbear==20.1.4',
39+
'flake8-logging-format==0.6.0',
40+
'flake8-implicit-str-concat==0.2.0',
41+
]
42+
3343
# We use the Python version instead of the original version which seems to require Docker
3444
# https://github.com/koalaman/shellcheck-precommit
3545
- repo: https://github.com/shellcheck-py/shellcheck-py
36-
rev: v0.8.0.1
46+
rev: v0.8.0.4
3747
hooks:
3848
- id: shellcheck
3949
name: shellcheck
4050
args: ["--severity=warning"]
51+
52+
- repo: https://github.com/sirosen/check-jsonschema
53+
rev: 0.11.0
54+
hooks:
55+
- id: check-jsonschema
56+
name: "Check GitHub Workflows"
57+
files: ^\.github/workflows/
58+
types: [yaml]
59+
args: ["--schemafile", "https://json.schemastore.org/github-workflow"]

bson/__init__.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@
8484
cast,
8585
)
8686

87-
from bson.binary import (
87+
from bson.binary import ( # noqa: F401
8888
ALL_UUID_SUBTYPES,
8989
CSHARP_LEGACY,
9090
JAVA_LEGACY,
@@ -513,7 +513,7 @@ def _bson_to_dict(data: Any, opts: Any) -> Any:
513513

514514

515515
if _USE_C:
516-
_bson_to_dict = _cbson._bson_to_dict
516+
_bson_to_dict = _cbson._bson_to_dict # noqa: F811
517517

518518

519519
_PACK_FLOAT = struct.Struct("<d").pack
@@ -543,15 +543,15 @@ def _make_c_string_check(string: Union[str, bytes]) -> bytes:
543543
"""Make a 'C' string, checking for embedded NUL characters."""
544544
if isinstance(string, bytes):
545545
if b"\x00" in string:
546-
raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character")
546+
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
547547
try:
548548
_utf_8_decode(string, None, True)
549549
return string + b"\x00"
550550
except UnicodeError:
551-
raise InvalidStringData("strings in documents must be valid " "UTF-8: %r" % string)
551+
raise InvalidStringData("strings in documents must be valid UTF-8: %r" % string)
552552
else:
553553
if "\x00" in string:
554-
raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character")
554+
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
555555
return cast(bytes, _utf_8_encode(string)[0]) + b"\x00"
556556

557557

@@ -562,7 +562,7 @@ def _make_c_string(string: Union[str, bytes]) -> bytes:
562562
_utf_8_decode(string, None, True)
563563
return string + b"\x00"
564564
except UnicodeError:
565-
raise InvalidStringData("strings in documents must be valid " "UTF-8: %r" % string)
565+
raise InvalidStringData("strings in documents must be valid UTF-8: %r" % string)
566566
else:
567567
return cast(bytes, _utf_8_encode(string)[0]) + b"\x00"
568568

@@ -571,7 +571,7 @@ def _make_name(string: str) -> bytes:
571571
"""Make a 'C' string suitable for a BSON key."""
572572
# Keys can only be text in python 3.
573573
if "\x00" in string:
574-
raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character")
574+
raise InvalidDocument("BSON keys / regex patterns must not contain a NUL character")
575575
return cast(bytes, _utf_8_encode(string)[0]) + b"\x00"
576576

577577

@@ -846,7 +846,7 @@ def _name_value_to_bson(
846846
def _element_to_bson(key: Any, value: Any, check_keys: bool, opts: Any) -> bytes:
847847
"""Encode a single key, value pair."""
848848
if not isinstance(key, str):
849-
raise InvalidDocument("documents must have only string keys, " "key was %r" % (key,))
849+
raise InvalidDocument("documents must have only string keys, key was %r" % (key,))
850850
if check_keys:
851851
if key.startswith("$"):
852852
raise InvalidDocument("key %r must not start with '$'" % (key,))
@@ -876,7 +876,7 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: Any, top_level: bool = True)
876876

877877

878878
if _USE_C:
879-
_dict_to_bson = _cbson._dict_to_bson
879+
_dict_to_bson = _cbson._dict_to_bson # noqa: F811
880880

881881

882882
def _millis_to_datetime(millis: int, opts: Any) -> datetime.datetime:
@@ -1032,7 +1032,7 @@ def decode_all(
10321032

10331033

10341034
if _USE_C:
1035-
decode_all = _cbson.decode_all
1035+
decode_all = _cbson.decode_all # noqa: F811
10361036

10371037

10381038
def _decode_selective(rawdoc: Any, fields: Any, codec_options: Any) -> Mapping[Any, Any]:

bson/binary.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ def from_uuid(
260260

261261
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
262262
raise ValueError(
263-
"uuid_representation must be a value " "from bson.binary.UuidRepresentation"
263+
"uuid_representation must be a value from bson.binary.UuidRepresentation"
264264
)
265265

266266
if uuid_representation == UuidRepresentation.UNSPECIFIED:
@@ -310,7 +310,7 @@ def as_uuid(self, uuid_representation: int = UuidRepresentation.STANDARD) -> UUI
310310

311311
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
312312
raise ValueError(
313-
"uuid_representation must be a value from " "bson.binary.UuidRepresentation"
313+
"uuid_representation must be a value from bson.binary.UuidRepresentation"
314314
)
315315

316316
if uuid_representation == UuidRepresentation.UNSPECIFIED:

bson/codec_options.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,10 @@
2323
Any,
2424
Callable,
2525
Dict,
26-
Generic,
2726
Iterable,
2827
MutableMapping,
2928
Optional,
3029
Type,
31-
TypeVar,
3230
Union,
3331
cast,
3432
)
@@ -312,10 +310,10 @@ def __new__(
312310
raise TypeError("tz_aware must be True or False")
313311
if uuid_representation not in ALL_UUID_REPRESENTATIONS:
314312
raise ValueError(
315-
"uuid_representation must be a value " "from bson.binary.UuidRepresentation"
313+
"uuid_representation must be a value from bson.binary.UuidRepresentation"
316314
)
317315
if not isinstance(unicode_decode_error_handler, (str, None)): # type: ignore
318-
raise ValueError("unicode_decode_error_handler must be a string " "or None")
316+
raise ValueError("unicode_decode_error_handler must be a string or None")
319317
if tzinfo is not None:
320318
if not isinstance(tzinfo, datetime.tzinfo):
321319
raise TypeError("tzinfo must be an instance of datetime.tzinfo")

bson/dbref.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(
3535
collection: str,
3636
id: Any,
3737
database: Optional[str] = None,
38-
_extra: Mapping[str, Any] = {},
38+
_extra: Optional[Mapping[str, Any]] = None,
3939
**kwargs: Any
4040
) -> None:
4141
"""Initialize a new :class:`DBRef`.
@@ -63,7 +63,7 @@ def __init__(
6363
self.__collection = collection
6464
self.__id = id
6565
self.__database = database
66-
kwargs.update(_extra)
66+
kwargs.update(_extra or {})
6767
self.__kwargs = kwargs
6868

6969
@property

bson/json_util.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ def __new__(
283283
self.json_mode = json_mode
284284
if self.json_mode == JSONMode.RELAXED:
285285
if strict_number_long:
286-
raise ValueError("Cannot specify strict_number_long=True with" " JSONMode.RELAXED")
286+
raise ValueError("Cannot specify strict_number_long=True with JSONMode.RELAXED")
287287
if datetime_representation not in (None, DatetimeRepresentation.ISO8601):
288288
raise ValueError(
289289
"datetime_representation must be DatetimeRepresentation."
@@ -296,7 +296,7 @@ def __new__(
296296
self.strict_uuid = True
297297
elif self.json_mode == JSONMode.CANONICAL:
298298
if strict_number_long not in (None, True):
299-
raise ValueError("Cannot specify strict_number_long=False with" " JSONMode.RELAXED")
299+
raise ValueError("Cannot specify strict_number_long=False with JSONMode.RELAXED")
300300
if datetime_representation not in (None, DatetimeRepresentation.NUMBERLONG):
301301
raise ValueError(
302302
"datetime_representation must be DatetimeRepresentation."
@@ -581,11 +581,9 @@ def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Union[Binary
581581
if not isinstance(b64, str):
582582
raise TypeError("$binary base64 must be a string: %s" % (doc,))
583583
if not isinstance(subtype, str) or len(subtype) > 2:
584-
raise TypeError("$binary subType must be a string at most 2 " "characters: %s" % (doc,))
584+
raise TypeError("$binary subType must be a string at most 2 characters: %s" % (doc,))
585585
if len(binary) != 2:
586-
raise TypeError(
587-
'$binary must include only "base64" and "subType" ' "components: %s" % (doc,)
588-
)
586+
raise TypeError('$binary must include only "base64" and "subType" components: %s' % (doc,))
589587

590588
data = base64.b64decode(b64.encode())
591589
return _binary_or_uuid(data, int(subtype, 16), json_options)
@@ -686,7 +684,7 @@ def _parse_canonical_regex(doc: Any) -> Regex:
686684
opts = regex["options"]
687685
if not isinstance(opts, str):
688686
raise TypeError(
689-
"Bad $regularExpression options, options must be " "string, was type %s" % (type(opts))
687+
"Bad $regularExpression options, options must be string, was type %s" % (type(opts))
690688
)
691689
return Regex(regex["pattern"], opts)
692690

bson/objectid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def __validate(self, oid: Any) -> None:
204204
_raise_invalid_id(oid)
205205
else:
206206
raise TypeError(
207-
"id must be an instance of (bytes, str, ObjectId), " "not %s" % (type(oid),)
207+
"id must be an instance of (bytes, str, ObjectId), not %s" % (type(oid),)
208208
)
209209

210210
@property

bson/raw_bson.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@
5151
overhead of decoding or encoding BSON.
5252
"""
5353

54-
from collections.abc import Mapping as _Mapping
55-
from typing import Any, ItemsView, Iterator, Mapping, Optional, cast
54+
from typing import Any, ItemsView, Iterator, Mapping, Optional
5655

5756
from bson import _get_object_size, _raw_to_dict
5857
from bson.codec_options import _RAW_BSON_DOCUMENT_MARKER

bson/tz_util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
"""Timezone related utilities for BSON."""
1616

1717
from datetime import datetime, timedelta, tzinfo
18-
from typing import Any, Optional, Tuple, Union
18+
from typing import Optional, Tuple, Union
1919

2020
ZERO: timedelta = timedelta(0)
2121

doc/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
sys.path[0:0] = [os.path.abspath("..")]
1111

12-
import pymongo
12+
import pymongo # noqa
1313

1414
# -- General configuration -----------------------------------------------------
1515

green_framework_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def run(framework_name, *args):
5959

6060
# Run the tests.
6161
sys.argv[:] = ["setup.py", "test"] + list(args)
62-
import setup
62+
import setup # noqa
6363

6464

6565
def main():
@@ -87,7 +87,7 @@ def main():
8787
list_frameworks()
8888
sys.exit()
8989
else:
90-
assert False, "unhandled option"
90+
raise AssertionError("unhandled option")
9191

9292
if not args:
9393
print(usage)

gridfs/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,10 @@
3535
)
3636
from pymongo import ASCENDING, DESCENDING
3737
from pymongo.client_session import ClientSession
38-
from pymongo.collation import Collation
3938
from pymongo.collection import Collection
40-
from pymongo.common import UNAUTHORIZED_CODES, validate_string
39+
from pymongo.common import validate_string
4140
from pymongo.database import Database
42-
from pymongo.errors import ConfigurationError, OperationFailure
41+
from pymongo.errors import ConfigurationError
4342
from pymongo.read_preferences import _ServerMode
4443
from pymongo.write_concern import WriteConcern
4544

@@ -83,7 +82,7 @@ def __init__(self, database: Database, collection: str = "fs"):
8382
database = _clear_entity_type_registry(database)
8483

8584
if not database.write_concern.acknowledged:
86-
raise ConfigurationError("database must use " "acknowledged write_concern")
85+
raise ConfigurationError("database must use acknowledged write_concern")
8786

8887
self.__collection = database[collection]
8988
self.__files = self.__collection.files

0 commit comments

Comments
 (0)