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

Simplify dictionary update #165

Closed
emorozov opened this issue Sep 29, 2021 · 3 comments
Closed

Simplify dictionary update #165

emorozov opened this issue Sep 29, 2021 · 3 comments
Labels
enhancement New feature or request next release This will be fixed in next release

Comments

@emorozov
Copy link

Issue description or question

I often see the code like:

def foo(d: dict) -> None:
   d.update({'request': HttpRequest()})
   frobnicate(d)

Here .update can and should be replaced with:

d['request'] = HttpRequest()

Sourcery Version

0.9.5

Code editor or IDE name and version

Pycharm v2021.2.2

OS name and version

Arch Linux (Linux lenovo 5.14.7-arch1-1 #1 SMP PREEMPT Wed, 22 Sep 2021 21:35:11 +0000 x86_64 GNU/Linux)

@Hellebore Hellebore added the enhancement New feature or request label Sep 29, 2021
@Hellebore
Copy link
Collaborator

yeah this looks like a nice little improvement

@ruancomelli
Copy link
Contributor

Be careful with multiple keys:

from typing import Dict

d1: Dict[str, int] = {'a': 0, 'b': 10}
d1.update({'a': d1['b'], 'b': d1['a']})
print(d1) # {'a': 10, 'b': 0}

d2: Dict[str, int] = {'a': 0, 'b': 10}
d2['a'] = d2['b']
d2['b'] = d2['a']
print(d2) # {'a': 10, 'b': 10}

Another possible refactoring here is when the "update_dict" keys are all str, in which case we can update the original dict using keyword arguments:

d1: Dict[str, int] = {'a': 0, 'b': 10}
d1.update({'a': d1['b'], 'b': d1['a']})
print(d1) # {'a': 10, 'b': 0}

d2: Dict[str, int] = {'a': 0, 'b': 10}
d2.update(a=d2['b'], b=d2['a'])
print(d2) # {'a': 10, 'b': 0}

@Hellebore Hellebore added the next release This will be fixed in next release label Oct 12, 2021
@Hellebore
Copy link
Collaborator

Added in 0.9.6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request next release This will be fixed in next release
Projects
None yet
Development

No branches or pull requests

3 participants