Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,20 @@ second usage. Save the result to a list if the result is needed multiple times.

**B040**: Caught exception with call to ``add_note`` not used. Did you forget to ``raise`` it?

.. _B041:

**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.

.. _B042:

**B042**: Remember to call super().__init__() in custom exceptions initalizer.

.. _B043:

**B043**: Do not call ``delattr(x, 'attr')``, instead use ``del x.attr``.
There is no additional safety in using ``delattr`` if you know the attribute name ahead of time.


Opinionated warnings
~~~~~~~~~~~~~~~~~~~~

Expand Down
13 changes: 13 additions & 0 deletions bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,13 @@ def visit_Call(self, node) -> None:
and not iskeyword(node.args[1].value)
):
self.add_error("B010", node)
elif (
node.func.id == "delattr"
and len(node.args) == 2
and _is_identifier(node.args[1])
and not iskeyword(node.args[1].value)
):
self.add_error("B043", node)

self.check_for_b026(node)
self.check_for_b028(node)
Expand Down Expand Up @@ -2415,6 +2422,12 @@ def __call__(self, lineno: int, col: int, vars: tuple[object, ...] = ()) -> erro
"It should also not take any kwargs."
)
),
"B043": Error(
message=(
"B043 Do not call delattr with a constant attribute value, "
"it is not any safer than normal property access."
)
),
# Warnings disabled by default.
"B901": Error(
message=(
Expand Down
11 changes: 11 additions & 0 deletions tests/eval_files/b043.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Valid usage
attr_name = "name"
delattr(obj, attr_name)
for field in fields_to_remove:
delattr(obj, field)
delattr(obj, some_name())
delattr(obj, f"field_{index}")

# Invalid usage
delattr(obj, "name") # B043: 0
delattr(obj, r"raw_attr") # B043: 0