flake8-bugbear
A plugin for flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.
Description
============== flake8-bugbear ============== .. image:: https://github.com/PyCQA/flake8-bugbear/actions/workflows/ci.yml/badge.svg :target: https://github.com/PyCQA/flake8-bugbear/actions/workflows/ci.yml .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black .. image:: https://results.pre-commit.ci/badge/github/PyCQA/flake8-bugbear/main.svg :target: https://results.pre-commit.ci/latest/github/PyCQA/flake8-bugbear/main :alt: pre-commit.ci status A plugin for ``flake8`` finding likely bugs and design problems in your program. Contains warnings that don't belong in ``pyflakes`` and ``pycodestyle``:: bugΒ·bear (bΕgβ²bΓ’rβ²) n. 1. A cause of fear, anxiety, or irritation: *Overcrowding is often a bugbear for train commuters.* 2. A difficult or persistent problem: *"One of the major bugbears of traditional AI is the difficulty of programming computers to recognize that different but similar objects are instances of the same type of thing" (Jack Copeland).* 3. A fearsome imaginary creature, especially one evoked to frighten children. It is felt that these lints don't belong in the main Python tools as they are very opinionated and do not have a PEP or standard behind them. Due to ``flake8`` being designed to be extensible, the original creators of these lints believed that a plugin was the best route. This has resulted in better development velocity for contributors and adaptive deployment for ``flake8`` users. Installation ------------ Install from ``pip`` with: .. code-block:: sh pip install flake8-bugbear It will then automatically be run as part of ``flake8``; you can check it has been picked up with: .. code-block:: sh $ flake8 --version 3.5.0 (assertive: 1.0.1, flake8-bugbear: 18.2.0, flake8-comprehensions: 1.4.1, mccabe: 0.6.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 3.7.0 on Darwin Development ----------- If you'd like to do a PR we have development instructions `here <https://github.com/PyCQA/flake8-bugbear/blob/master/DEVELOPMENT.md>`_. List of warnings ---------------- .. _B001: **B001**: Do not use bare ``except:``, it also catches unexpected events like memory errors, interrupts, system exit, and so on. Prefer ``except Exception:``. If you're sure what you're doing, be explicit and write ``except BaseException:``. Disable ``E722`` to avoid duplicate warnings. .. _B002: **B002**: Python does not support the unary prefix increment. Writing ``++n`` is equivalent to ``+(+(n))``, which equals ``n``. You meant ``n += 1``. .. _B003: **B003**: Assigning to ``os.environ`` doesn't clear the environment. Subprocesses are going to see outdated variables, in disagreement with the current process. Use ``os.environ.clear()`` or the ``env=`` argument to Popen. .. _B004: **B004**: Using ``hasattr(x, '__call__')`` to test if ``x`` is callable is unreliable. If ``x`` implements custom ``__getattr__`` or its ``__call__`` is itself not callable, you might get misleading results. Use ``callable(x)`` for consistent results. .. _B005: **B005**: Using ``.strip()`` with multi-character strings is misleading the reader. It looks like stripping a substring. Move your character set to a constant if this is deliberate. Use ``.replace()``, ``.removeprefix()``, ``.removesuffix()`` or regular expressions to remove string fragments. .. _B006: **B006**: Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them. .. _B007: **B007**: Loop control variable not used within the loop body. If this is intended, start the name with an underscore. .. _B008: **B008**: Do not perform function calls in argument defaults. The call is performed only once at function definition time. All calls to your function will reuse the result of that definition-time function call. If this is intended, assign the function call to a module-level variable and use that variable as a default value. .. _B009: **B009**: Do not call ``getattr(x, 'attr')``, instead use normal property access: ``x.attr``. Missing a default to ``getattr`` will cause an ``AttributeError`` to be raised for non-existent properties. There is no additional safety in using ``getattr`` if you know the attribute name ahead of time. .. _B010: **B010**: Do not call ``setattr(x, 'attr', val)``, instead use normal property access: ``x.attr = val``. There is no additional safety in using ``setattr`` if you know the attribute name ahead of time. .. _B011: **B011**: Do not call ``assert False`` since ``python -O`` removes these calls. Instead callers should ``raise AssertionError()``. .. _B012: **B012**: Use of ``break``, ``continue`` or ``return`` inside ``finally`` blocks will silence exceptions or override return values from the ``try`` or ``except`` blocks. To s
Release History
| Version | Changes | Urgency | Date |
|---|---|---|---|
| 25.11.29 | Imported from PyPI (25.11.29) | Low | 4/21/2026 |
| 25.10.21 | * B042: New check for reminding to call super().__init__ in custom exceptions * B028: Skip if skip_file_prefixes is used (#503) * B912: New check for `map()` without an explicit `strict=` parameter. (#516) * Add python3.14 Support / CI * Remove python3.9 support / CI * flake8-bugbear now requires at least Python 3.10, like the next release of flake8 | Low | 10/22/2025 |
| 24.12.12 | * B012 and B025 now also handle try/except* (#500) * Skip B028 if warnings.warn is called with ``*args`` or ``**kwargs`` (#501) * Add B911: itertools.batched without strict= (#502) * Readme has anchors per check (they do not seem to render on GitHub tho) | Low | 12/12/2024 |
| 24.10.31 | * B041: New dictionary same key AND value check (#496) * B037: Fix typo in error message * B024: No longer treats assigned class variables as abstract (#471) * Bump required attrs version to 22.2.0 | Low | 10/31/2024 |
| 24.8.19 | * B910: implement to suggest using Counter() instead of defaultdict(int) (#489) * B901: Do not trigger with explicit Generator return type (#481) * B008: add some comments, rename b008_extend_immutable_calls (#476) * B040: exception with note added not reraised or used (#477) * B039, Add ``ContextVar`` with mutable literal or function call as default * B040: Add Exception with added note not reraised. (#474) * Run tests in Python 3.13 * Type annotated code (#481 + #483) * Replace hash wi | Low | 8/20/2024 |
| 24.4.26 | * B909: Fix false positive affecting containers of mutables (#469) | Low | 4/26/2024 |
| 24.4.21 | * B950: Add pragma comment to line length ignores (#463) * B909: Add more cases to detect + more container mutating functions (#460) | Low | 4/21/2024 |
| 24.2.6 | * B902: Remove decorators named validator and root_validator from B902 checks (#459) * B038: Change B038 to B909 and make it optional (#456) | Low | 2/7/2024 |
| 24.1.17 | * B038: Restrict rule to mutation functions only (#453) | Low | 1/17/2024 |
| 24.1.16 | * B036: Fix crash on ``raise`` statements raising something other than | Low | 1/16/2024 |
| 24.1.15 | * B038: Add check for mutations of loop iterator (#446) * B037: Add check for yielding or returning values in __init__() (#442) * B017: make B017 also apply to BaseException (#439) * B036: Add check for except BaseException without re-raising (#438) | Low | 1/15/2024 |
| 23.12.2 | * B018: to detect useless-statements at all levels (#434) * B018: Add classname to b018 useless-expression output (#433) * B018: Include tuples in b018 useless-statement check (#432) | Low | 12/2/2023 |
| 23.11.28 | * B035: Fix false positive when named expressions are used (#430) | Low | 11/29/2023 |
| 23.11.26 | * B035: add check for static keys in dict-comprehension (#426) * B902: Add exceptions for standard library metaclasses (#415) * B017: Modify to no longer have a false negative when raises() is imported directly from pytest (#424) * B026: Fix bug where the check was not triggered for calls where the caller is an attribute (#420) | Low | 11/27/2023 |
| 23.9.16 | * add --classmethod-decorators (#405) * fix name collision for node_stack on python 3.12 (#406) * Use pypa/build to build the package (#404) | Low | 9/16/2023 |
| 23.7.10 | * Add B034: re.sub/subn/split must pass flags/count/maxsplit as keyword arguments. * Fix a crash and several test failures on Python 3.12, all relating to the B907 check. * Declare support for Python 3.12. | Low | 7/10/2023 |
| 23.6.5 | * Include tox.ini in MANIFEST.in for sdist. (#389) * Improve B033 (duplicate set items) (#385) | Low | 6/5/2023 |
| 23.5.9 | * Add B033: Detect duplicate items in sets * Add B908: Detect assertRauses like contexts only has top level statements that could throw * Add B028: Allow stacklevel to be explicitly assigned as a positional argument * Remove more < 3.8 checks / assertions | Low | 5/9/2023 |
| 23.3.23 | * flake8-bugbear is now >= 3.8.1 project like flake8>=6.0.0 * This has allowed some more modern AST usage cleanup and less CI running etc. * B030: Fix crash on certain unusual except handlers (e.g. ``except a[0].b:``) | Low | 3/23/2023 |
| 23.3.12 | * B950: now ignores 'noqa' and 'type: ignore' comments. * B005: Do not flag when using the ``strip()`` method on an imported module. * B030: Allow calls and starred expressions in except handlers. | Low | 3/12/2023 |
| 23.2.13 | * B906: Add ``visit_Bytes``, ``visit_Num`` and ``visit_Str`` to the list of ``visit_*`` functions that are ignored by the B906 check. The ``ast.Bytes``, ``ast.Num`` and ``ast.Str`` nodes are all deprecated, but may still be used by some codebases in order to maintain backwards compatibility with Python 3.7. * B016: Warn when raising f-strings. * Add B028: Check for an explicit stacklevel keyword argument on the warn method from the warnings module. * Add B029: Check when trying to us | Low | 2/13/2023 |
| 23.1.20 | * B024: now ignores classes without any methods. (#336) * B017: Don't warn when ``pytest.raises()`` has a ``match`` argument. (#334) * B906: Ignore ``visit_`` functions with a ``_fields`` attribute that can't contain ast.AST subnodes. (#330) | Low | 1/20/2023 |
| 23.1.17 | * Rename B028 to B907, making it optional/opinionated. | Low | 1/18/2023 |
| 23.1.14 | * Add B906: ``visit_`` function with no further calls to a ``visit`` function. (#313) * Add B028: Suggest ``!r`` when formatted value in f-string is surrounded by quotes. (#319) | Low | 1/14/2023 |
| 22.12.6 | * Add B905: `zip()` without an explicit `strict=` parameter. (#314) * B027: ignore @overload when typing is imported with other names (#309) | Low | 12/6/2022 |
| 22.10.27 | * B027: Ignore @overload decorator (#306) * B023: Also fix map (#305) * B023: Avoid false alarms with filter, reduce, key= and return. Added tests for functools (#303) | Low | 10/26/2022 |
| 22.10.25 | * Make B015 and B018 messages slightly more polite (#298) * Add B027: Empty method in abstract base class with no abstract decorator * Multiple B024 false positive fixes * Move CI to use `tox` (#294) * Move to using PEP621 / `pyproject.toml` package (#291) * Tested in 3.11 | Low | 10/24/2022 |
| 22.9.23 | * add B026: find argument unpacking after keyword argument (#287) * Move to setup.cfg like flake8 (#288) | Low | 9/23/2022 |
| 22.9.11 | * Add B025: Find duplicate except clauses (#284) | Low | 9/11/2022 |
| 22.8.23 | * Add B024 error code to message for B024 (#276) | Low | 8/23/2022 |
| 22.8.22 | * Add B024: abstract base class with no abstract methods (#273) | Low | 8/22/2022 |
| 22.7.1 | * Implement late-binding loop check (#265) * [late-binding closures are a classic gotcha](https://docs.python-guide.org/writing/gotchas/#late-binding-closures>). | Low | 7/1/2022 |
| 22.6.22 | * Don't crash when select / extend_select are None (#261) * Unlocks new flake8 release - Thanks @asottile * Ignore lambda arguments for B020 (#259) * Fix missing space typos in B021, B022 error messages (#257) | Low | 6/23/2022 |
| 22.4.25 | * Ignore black formatting for b013 test case (#251) * B010 Fix lambda false positive (#246) * B008 Fix edge case with lambda functions (#243) | Low | 4/25/2022 |
| 22.3.23 | * B006 and B008: Detect function calls at any level of the default expression (#239) * B020: Fix comprehension false postives (#238) * Tweak B019 desc (#237) | Low | 3/23/2022 |
| 22.3.20 | * B022: No arguments passed to contextlib.suppress (#231) * B021: f-string used as docstring. (#230) * B020: ensure loop control variable doesn't overrides iterable it iterates (#220) * B019: check to find cache decorators on class methods (#218) * Fix crash on long empty string (#223) | Low | 3/20/2022 |
| 22.1.11 | * B018: Ignore JoinedStr (#216) * Build universal Python 3 wheels (#214) * B950: Add same special cases as E501 (#213) | Low | 1/12/2022 |
| 21.11.29 | * B018: Disable strings from check for now (#209) | Low | 11/29/2021 |
| 21.11.28 | * B904: ensure the raise is in the same context with the except (#191) * Add Option to extend the list of immutable calls (#204) * Update B014: ``binascii.Error`` is now treated as a subclass of ``ValueError`` (#206) * add simple pre-commit config (#205) * Test with 3.10 official * Add B018 check to find useless declarations (#196, #202) | Low | 11/28/2021 |
| 21.9.2 | * Fix crash on call in except statement in _to_name_str (#187) * Update B006: list, dictionary, and set comprehensions are now also disallowed (#186) | Low | 9/29/2021 |
| 21.9.1 | * Update B008: Whitelist more immutable function calls (#173) * Remove Python Compatibility Warnings (#182) * Add B904: check for ``raise`` without ``from`` in an ``except`` clause (#181) * Add Python 3.10 tests to ensure we pass (#183) | Low | 9/12/2021 |
| 21.4.3 | Verify the element in item_context.args is of type ast.Name for b017 | Low | 4/1/2021 |
| 21.4.2 | - Add another hasattr() check to b017 visit for .func | Low | 4/1/2021 |
| 21.4.1 | Happy April Fools! This is no joke, it's a real release. - Add B017: check for gotta-catch-em-all assertRaises(Exception) Catching them all is bad! | Low | 4/1/2021 |
| 21.3.2 | - Fix crash on tuple expansion in try/except block (#161) | Low | 3/8/2021 |
| 21.3.1 | - Fix grammar in B015 (#150) - Make sure float infinity/NaN does not trigger B008 (#155) - Handle positional-only args in class methods (#158) | Low | 3/3/2021 |
| 20.11.1 | - Support exception aliases properly in B014 (#129) - Add B015: Pointless comparison (#130) - Remove check for # noqa comments (#134) - Ignore exception classes which are not types (#135) - Introduce B016 to check for raising a literal. (#141) - Exclude types.MappingProxyType() from B008. (#144) | Low | 11/23/2020 |
| 20.1.4 | - Ignore keywords for B009/B010 | Low | 2/1/2020 |
| 20.1.3 | - Silence B009/B010 for non-identifiers - State an ignore might be needed for optional B9x checks | Low | 1/29/2020 |
| 20.1.2 | Refer to README.rst for changes. | Low | 1/6/2020 |
