Skip to content

Commit

Permalink
fix(b909): Allow mutation of dict[key] form
Browse files Browse the repository at this point in the history
These changes allow the following:
```
some_dict = {"foo": "bar"}
for key in some_dict:
    some_dict[key] = 3 # no error (previously error'd)
```
  • Loading branch information
mimre25 committed Apr 26, 2024
1 parent 65c86b0 commit 1b659f6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
8 changes: 6 additions & 2 deletions bugbear.py
Original file line number Diff line number Diff line change
Expand Up @@ -1581,11 +1581,13 @@ def check(num_args, param_name):
def check_for_b909(self, node: ast.For):
if isinstance(node.iter, ast.Name):
name = _to_name_str(node.iter)
key = _to_name_str(node.target)
elif isinstance(node.iter, ast.Attribute):
name = _to_name_str(node.iter)
key = _to_name_str(node.target)
else:
return
checker = B909Checker(name)
checker = B909Checker(name, key)
checker.visit(node.body)
for mutation in itertools.chain.from_iterable(
m for m in checker.mutations.values()
Expand Down Expand Up @@ -1624,8 +1626,9 @@ class B909Checker(ast.NodeVisitor):
"discard",
)

def __init__(self, name: str):
def __init__(self, name: str, key: str):
self.name = name
self.key = key
self.mutations = defaultdict(list)
self._conditional_block = 0

Expand All @@ -1634,6 +1637,7 @@ def visit_Assign(self, node: ast.Assign):
if (
isinstance(target, ast.Subscript)
and _to_name_str(target.value) == self.name
and _to_name_str(target.slice) != self.key
):
self.mutations[self._conditional_block].append(node)
self.generic_visit(node)
Expand Down
21 changes: 20 additions & 1 deletion tests/b909.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,23 @@ def __init__(self, ls):

lst: list[dict] = [{}, {}, {}]
for dic in lst:
dic["key"] = False
dic["key"] = False # no error



for grammar in grammars:
errors[grammar.version] = InvalidInput() # no error



for key in self.hpo_params:
if key in nni_config:
nni_config[key] = self.hpo_params[key] # no error


some_dict = {"foo": "bar"}
for key in some_dict:
some_dict[key] = 3 # no error

for key in some_dict.keys():
some_dict[key] = 3 # no error

0 comments on commit 1b659f6

Please sign in to comment.