Skip to content

Add B043: Do not call delattr with constant #514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,11 @@ second usage. Save the result to a list if the result is needed multiple times.

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

.. _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 @@ -2332,6 +2339,12 @@ def __call__(self, lineno: int, col: int, vars: tuple[object, ...] = ()) -> erro
message="B040 Exception with added note not used. Did you forget to raise it?"
),
"B041": Error(message=("B041 Repeated key-value pair in dictionary literal.")),
"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