Skip to content

Commit 7ee1976

Browse files
jtojnarcooperlees
andauthored
README: Add anchors for rules and config options (#491)
This will allow us to link to them directly. Co-authored-by: Cooper Lees <[email protected]>
1 parent b960272 commit 7ee1976

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

README.rst

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,76 +58,110 @@ If you'd like to do a PR we have development instructions `here <https://github.
5858
List of warnings
5959
----------------
6060

61+
.. _B001:
62+
6163
**B001**: Do not use bare ``except:``, it also catches unexpected events
6264
like memory errors, interrupts, system exit, and so on. Prefer ``except
6365
Exception:``. If you're sure what you're doing, be explicit and write
6466
``except BaseException:``. Disable ``E722`` to avoid duplicate warnings.
6567

68+
.. _B002:
69+
6670
**B002**: Python does not support the unary prefix increment. Writing
6771
``++n`` is equivalent to ``+(+(n))``, which equals ``n``. You meant ``n
6872
+= 1``.
6973

74+
.. _B003:
75+
7076
**B003**: Assigning to ``os.environ`` doesn't clear the
7177
environment. Subprocesses are going to see outdated
7278
variables, in disagreement with the current process. Use
7379
``os.environ.clear()`` or the ``env=`` argument to Popen.
7480

81+
.. _B004:
82+
7583
**B004**: Using ``hasattr(x, '__call__')`` to test if ``x`` is callable
7684
is unreliable. If ``x`` implements custom ``__getattr__`` or its
7785
``__call__`` is itself not callable, you might get misleading
7886
results. Use ``callable(x)`` for consistent results.
7987

88+
.. _B005:
89+
8090
**B005**: Using ``.strip()`` with multi-character strings is misleading
8191
the reader. It looks like stripping a substring. Move your
8292
character set to a constant if this is deliberate. Use
8393
``.replace()``, ``.removeprefix()``, ``.removesuffix()`` or regular
8494
expressions to remove string fragments.
8595

96+
.. _B006:
97+
8698
**B006**: Do not use mutable data structures for argument defaults. They
8799
are created during function definition time. All calls to the function
88100
reuse this one instance of that data structure, persisting changes
89101
between them.
90102

103+
.. _B007:
104+
91105
**B007**: Loop control variable not used within the loop body. If this is
92106
intended, start the name with an underscore.
93107

108+
.. _B008:
109+
94110
**B008**: Do not perform function calls in argument defaults. The call is
95111
performed only once at function definition time. All calls to your
96112
function will reuse the result of that definition-time function call. If
97113
this is intended, assign the function call to a module-level variable and
98114
use that variable as a default value.
99115

116+
.. _B009:
117+
100118
**B009**: Do not call ``getattr(x, 'attr')``, instead use normal
101119
property access: ``x.attr``. Missing a default to ``getattr`` will cause
102120
an ``AttributeError`` to be raised for non-existent properties. There is
103121
no additional safety in using ``getattr`` if you know the attribute name
104122
ahead of time.
105123

124+
.. _B010:
125+
106126
**B010**: Do not call ``setattr(x, 'attr', val)``, instead use normal
107127
property access: ``x.attr = val``. There is no additional safety in
108128
using ``setattr`` if you know the attribute name ahead of time.
109129

130+
.. _B011:
131+
110132
**B011**: Do not call ``assert False`` since ``python -O`` removes these calls.
111133
Instead callers should ``raise AssertionError()``.
112134

135+
.. _B012:
136+
113137
**B012**: Use of ``break``, ``continue`` or ``return`` inside ``finally`` blocks will
114138
silence exceptions or override return values from the ``try`` or ``except`` blocks.
115139
To silence an exception, do it explicitly in the ``except`` block. To properly use
116140
a ``break``, ``continue`` or ``return`` refactor your code so these statements are not
117141
in the ``finally`` block.
118142

143+
.. _B013:
144+
119145
**B013**: A length-one tuple literal is redundant. Write ``except SomeError:``
120146
instead of ``except (SomeError,):``.
121147

148+
.. _B014:
149+
122150
**B014**: Redundant exception types in ``except (Exception, TypeError):``.
123151
Write ``except Exception:``, which catches exactly the same exceptions.
124152

153+
.. _B015:
154+
125155
**B015**: Pointless comparison. This comparison does nothing but
126156
waste CPU instructions. Either prepend ``assert`` or remove it.
127157

158+
.. _B016:
159+
128160
**B016**: Cannot raise a literal. Did you intend to return it or raise
129161
an Exception?
130162

163+
.. _B017:
164+
131165
**B017**: ``assertRaises(Exception)`` and ``pytest.raises(Exception)`` should
132166
be considered evil. They can lead to your test passing even if the
133167
code being tested is never executed due to a typo. Assert for a more
@@ -136,73 +170,119 @@ specific exception (builtin or custom), or use ``assertRaisesRegex``
136170
using ``pytest.raises``), or use the context manager form with a target
137171
(e.g. ``with self.assertRaises(Exception) as ex:``).
138172

173+
.. _B018:
174+
139175
**B018**: Found useless expression. Either assign it to a variable or remove it.
140176
Note that dangling commas will cause things to be interpreted as useless tuples.
141177
For example, in the statement ``print(".."),`` is the same as ``(print(".."),)``
142178
which is an unassigned tuple. Simply remove the comma to clear the error.
143179

180+
.. _B019:
181+
144182
**B019**: Use of ``functools.lru_cache`` or ``functools.cache`` on methods
145183
can lead to memory leaks. The cache may retain instance references, preventing
146184
garbage collection.
147185

186+
.. _B020:
187+
148188
**B020**: Loop control variable overrides iterable it iterates
149189

190+
.. _B021:
191+
150192
**B021**: f-string used as docstring. This will be interpreted by python
151193
as a joined string rather than a docstring.
152194

195+
.. _B022:
196+
153197
**B022**: No arguments passed to `contextlib.suppress`.
154198
No exceptions will be suppressed and therefore this context manager is redundant.
155199
N.B. this rule currently does not flag `suppress` calls to avoid potential false
156200
positives due to similarly named user-defined functions.
157201

202+
.. _B023:
203+
158204
**B023**: Functions defined inside a loop must not use variables redefined in
159205
the loop, because `late-binding closures are a classic gotcha
160206
<https://docs.python-guide.org/writing/gotchas/#late-binding-closures>`__.
161207

208+
.. _B024:
209+
162210
**B024**: Abstract base class has methods, but none of them are abstract. This
163211
is not necessarily an error, but you might have forgotten to add the @abstractmethod
164212
decorator, potentially in conjunction with @classmethod, @property and/or @staticmethod.
165213

214+
.. _B025:
215+
166216
**B025**: ``try-except`` block with duplicate exceptions found.
167217
This check identifies exception types that are specified in multiple ``except``
168218
clauses. The first specification is the only one ever considered, so all others can be removed.
169219

220+
.. _B026:
221+
170222
**B026**: Star-arg unpacking after a keyword argument is strongly discouraged, because
171223
it only works when the keyword parameter is declared after all parameters supplied by
172224
the unpacked sequence, and this change of ordering can surprise and mislead readers.
173225
There was `cpython discussion of disallowing this syntax
174226
<https://github.com/python/cpython/issues/82741>`_, but legacy usage and parser
175227
limitations make it difficult.
176228

229+
.. _B027:
230+
177231
**B027**: Empty method in abstract base class, but has no abstract decorator. Consider adding @abstractmethod.
178232

233+
.. _B028:
234+
179235
**B028**: No explicit stacklevel argument found. The warn method from the warnings module uses a
180236
stacklevel of 1 by default. This will only show a stack trace for the line on which the warn method is called.
181237
It is therefore recommended to use a stacklevel of 2 or greater to provide more information to the user.
182238

239+
.. _B029:
240+
183241
**B029**: Using ``except ():`` with an empty tuple does not handle/catch anything. Add exceptions to handle.
184242

243+
.. _B030:
244+
185245
**B030**: Except handlers should only be exception classes or tuples of exception classes.
186246

247+
.. _B031:
248+
187249
**B031**: Using the generator returned from `itertools.groupby()` more than once will do nothing on the
188250
second usage. Save the result to a list if the result is needed multiple times.
189251

252+
.. _B032:
253+
190254
**B032**: Possible unintentional type annotation (using ``:``). Did you mean to assign (using ``=``)?
191255

256+
.. _B033:
257+
192258
**B033**: Sets should not contain duplicate items. Duplicate items will be replaced with a single item at runtime.
193259

260+
.. _B034:
261+
194262
**B034**: Calls to `re.sub`, `re.subn` or `re.split` should pass `flags` or `count`/`maxsplit` as keyword arguments. It is commonly assumed that `flags` is the third positional parameter, forgetting about `count`/`maxsplit`, since many other `re` module functions are of the form `f(pattern, string, flags)`.
195263

264+
.. _B035:
265+
196266
**B035**: Found dict comprehension with a static key - either a constant value or variable not from the comprehension expression. This will result in a dict with a single key that was repeatedly overwritten.
197267

268+
.. _B036:
269+
198270
**B036**: Found ``except BaseException:`` without re-raising (no ``raise`` in the top-level of the ``except`` block). This catches all kinds of things (Exception, SystemExit, KeyboardInterrupt...) and may prevent a program from exiting as expected.
199271

272+
.. _B037:
273+
200274
**B037**: Found ``return <value>``, ``yield``, ``yield <value>``, or ``yield from <value>`` in class ``__init__()`` method. No values should be returned or yielded, only bare ``return``\s are ok.
201275

276+
.. _B038:
277+
202278
**B038**: **Moved to B909** - Found a mutation of a mutable loop iterable inside the loop body. Changes to the iterable of a loop such as calls to `list.remove()` or via `del` can cause unintended bugs.
203279

280+
.. _B039:
281+
204282
**B039**: ``ContextVar`` with mutable literal or function call as default. This is only evaluated once, and all subsequent calls to `.get()` would return the same instance of the default. This uses the same logic as B006 and B008, including ignoring values in ``extend-immutable-calls``.
205283

284+
.. _B040:
285+
206286
**B040**: Caught exception with call to ``add_note`` not used. Did you forget to ``raise`` it?
207287

208288
**B041**: Repeated key-value pair in dictionary literal. Only emits errors when the key's value is *also* the same, being the opposite of the pyflakes like check.
@@ -215,29 +295,39 @@ controversial. They may or may not apply to you, enable them explicitly
215295
in your configuration if you find them useful. Read below on how to
216296
enable.
217297

298+
.. _B901:
299+
218300
**B901**: Using ``return x`` in a generator function used to be
219301
syntactically invalid in Python 2. In Python 3 ``return x`` can be used
220302
in a generator as a return value in conjunction with ``yield from``.
221303
Users coming from Python 2 may expect the old behavior which might lead
222304
to bugs. Use native ``async def`` coroutines or mark intentional
223305
``return x`` usage with ``# noqa`` on the same line.
224306

307+
.. _B902:
308+
225309
**B902**: Invalid first argument used for method. Use ``self`` for
226310
instance methods, and ``cls`` for class methods (which includes ``__new__``
227311
and ``__init_subclass__``) or instance methods of metaclasses (detected as
228312
classes directly inheriting from ``type``).
229313

314+
.. _B903:
315+
230316
**B903**: Use ``collections.namedtuple`` (or ``typing.NamedTuple``) for
231317
data classes that only set attributes in an ``__init__`` method, and do
232318
nothing else. If the attributes should be mutable, define the attributes
233319
in ``__slots__`` to save per-instance memory and to prevent accidentally
234320
creating additional attributes on instances.
235321

322+
.. _B904:
323+
236324
**B904**: Within an ``except`` clause, raise exceptions with ``raise ... from err``
237325
or ``raise ... from None`` to distinguish them from errors in exception handling.
238326
See `the exception chaining tutorial <https://docs.python.org/3/tutorial/errors.html#exception-chaining>`_
239327
for details.
240328

329+
.. _B905:
330+
241331
**B905**: ``zip()`` without an explicit `strict=` parameter set. ``strict=True`` causes the resulting iterator
242332
to raise a ``ValueError`` if the arguments are exhausted at differing lengths.
243333

@@ -246,22 +336,36 @@ Exclusions are `itertools.count <https://docs.python.org/3/library/itertools.htm
246336
The ``strict=`` argument was added in Python 3.10, so don't enable this flag for code that should work on <3.10.
247337
For more information: https://peps.python.org/pep-0618/
248338

339+
.. _B906:
340+
249341
**B906**: ``visit_`` function with no further call to a ``visit`` function. This is often an error, and will stop the visitor from recursing into the subnodes of a visited node. Consider adding a call ``self.generic_visit(node)`` at the end of the function.
250342
Will only trigger on function names where the part after ``visit_`` is a valid ``ast`` type with a non-empty ``_fields`` attribute.
251343
This is meant to be enabled by developers writing visitors using the ``ast`` module, such as flake8 plugin writers.
252344

345+
.. _B907:
346+
253347
**B907**: Consider replacing ``f"'{foo}'"`` with ``f"{foo!r}"`` which is both easier to read and will escape quotes inside ``foo`` if that would appear. The check tries to filter out any format specs that are invalid together with ``!r``. If you're using other conversion flags then e.g. ``f"'{foo!a}'"`` can be replaced with ``f"{ascii(foo)!r}"``. Not currently implemented for python<3.8 or ``str.format()`` calls.
254348

349+
.. _B908:
350+
255351
**B908**: Contexts with exceptions assertions like ``with self.assertRaises`` or ``with pytest.raises`` should not have multiple top-level statements. Each statement should be in its own context. That way, the test ensures that the exception is raised only in the exact statement where you expect it.
256352

353+
.. _B909:
354+
257355
**B909**: **Was B038** - Found a mutation of a mutable loop iterable inside the loop body. Changes to the iterable of a loop such as calls to `list.remove()` or via `del` can cause unintended bugs.
258356

357+
.. _B910:
358+
259359
**B910**: Use Counter() instead of defaultdict(int) to avoid excessive memory use as the default dict will record missing keys with the default value when accessed.
260360

361+
.. _B911:
362+
261363
**B911**: ``itertools.batched()`` without an explicit `strict=` parameter set. ``strict=True`` causes the resulting iterator to raise a ``ValueError`` if the final batch is shorter than ``n``.
262364

263365
The ``strict=`` argument was added in Python 3.13, so don't enable this flag for code that should work on <3.13.
264366

367+
.. _B950:
368+
265369
**B950**: Line too long. This is a pragmatic equivalent of
266370
``pycodestyle``'s ``E501``: it considers "max-line-length" but only triggers
267371
when the value has been exceeded by **more than 10%**. ``noqa`` and ``type: ignore`` comments are ignored. You will no
@@ -324,11 +428,15 @@ Configuration
324428

325429
The plugin currently has the following settings:
326430

431+
.. _extend_immutable_calls:
432+
327433
``extend-immutable-calls``: Specify a list of additional immutable calls.
328434
This could be useful, when using other libraries that provide more immutable calls,
329435
beside those already handled by ``flake8-bugbear``. Calls to these method will no longer
330436
raise a ``B008`` or ``B039`` warning.
331437

438+
.. _classmethod_decorators:
439+
332440
``classmethod-decorators``: Specify a list of decorators to additionally mark a method as a ``classmethod`` as used by B902. The default only checks for ``classmethod``. When an ``@obj.name`` decorator is specified it will match against either ``name`` or ``obj.name``.
333441
This functions similarly to how `pep8-naming <https://github.com/PyCQA/pep8-naming>` handles it, but with different defaults, and they don't support specifying attributes such that a decorator will never match against a specified value ``obj.name`` even if decorated with ``@obj.name``.
334442

0 commit comments

Comments
 (0)