Skip to content

Commit 2d2fd4d

Browse files
authored
Add B043: Do not call delattr with constant (#514)
1 parent 9677fa8 commit 2d2fd4d

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

README.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,10 +286,20 @@ second usage. Save the result to a list if the result is needed multiple times.
286286

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

289+
.. _B041:
290+
289291
**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.
290292

293+
.. _B042:
294+
291295
**B042**: Remember to call super().__init__() in custom exceptions initalizer.
292296

297+
.. _B043:
298+
299+
**B043**: Do not call ``delattr(x, 'attr')``, instead use ``del x.attr``.
300+
There is no additional safety in using ``delattr`` if you know the attribute name ahead of time.
301+
302+
293303
Opinionated warnings
294304
~~~~~~~~~~~~~~~~~~~~
295305

bugbear.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,13 @@ def visit_Call(self, node) -> None:
523523
and not iskeyword(node.args[1].value)
524524
):
525525
self.add_error("B010", node)
526+
elif (
527+
node.func.id == "delattr"
528+
and len(node.args) == 2
529+
and _is_identifier(node.args[1])
530+
and not iskeyword(node.args[1].value)
531+
):
532+
self.add_error("B043", node)
526533

527534
self.check_for_b026(node)
528535
self.check_for_b028(node)
@@ -2415,6 +2422,12 @@ def __call__(self, lineno: int, col: int, vars: tuple[object, ...] = ()) -> erro
24152422
"It should also not take any kwargs."
24162423
)
24172424
),
2425+
"B043": Error(
2426+
message=(
2427+
"B043 Do not call delattr with a constant attribute value, "
2428+
"it is not any safer than normal property access."
2429+
)
2430+
),
24182431
# Warnings disabled by default.
24192432
"B901": Error(
24202433
message=(

tests/eval_files/b043.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Valid usage
2+
attr_name = "name"
3+
delattr(obj, attr_name)
4+
for field in fields_to_remove:
5+
delattr(obj, field)
6+
delattr(obj, some_name())
7+
delattr(obj, f"field_{index}")
8+
9+
# Invalid usage
10+
delattr(obj, "name") # B043: 0
11+
delattr(obj, r"raw_attr") # B043: 0

0 commit comments

Comments
 (0)