Skip to content
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

Add back list() when iterating over d.items() in a for statement #262

Open
wants to merge 1 commit into
base: master
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 0 additions & 6 deletions modernize/fixes/fix_dict_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,3 @@ def transform(self, node, results):
return super().transform(node, results)
else:
return self.transform_iter(node, results)

def in_special_context(self, node, isiter):
# Redefined from parent class to make "for x in d.items()" count as
# in special context; fissix only counts for loops as special context
# for the iter* methods.
return super().in_special_context(node, True)
6 changes: 3 additions & 3 deletions tests/test_fix_dict_six.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@
DICT_IN_LOOP = (
"""\
for k in x.items():
pass
del x[k]
""",
"""\
for k in x.items():
pass
for k in list(x.items()):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

really this should be for k in x.copy().items(): because list(x.items()) isn't threadsafe when x.items() was threadsafe on Python 2

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That’s something to consider. copy() does have the advantage of being atomic and being about 10% faster:

# python3.9
>>> import timeit
>>> timeit.timeit(setup='d = dict(zip(range(10000), range(10000)))', stmt='sum(d.copy().keys())', number=10000)
0.814354999999999
>>> timeit.timeit(setup='d = dict(zip(range(10000), range(10000)))', stmt='sum(list(d.keys()))', number=10000)
0.9197422089999989

Downsides of switching to copy():

The point of this PR is to restore the 2to3 fix_dict behavior which identifies all the items(), keys(), and values() that may need to change. After manual review, you may find statements where the list() is unnecessary (and you could have used iteritems() before) or you may switch to d.copy() for concurrency and performance. I think changing from list() to .copy() warrants a separate PR.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@graingert are you requesting me to change it to .copy()?

del x[k]
""",
)

Expand Down