I came across a bug today that involved the re-definition of a dictionary that was being looped over within the loop. A simple example is something like:
```
my_dict = {"a": 1, "b": 2, "c": 3}
some_other_dict = {"x": 99}
for key in my_dict.keys():
print(my_dict[key])
my_dict = some_other_dict
```
Python continues to iterate over the original `my_dict`, but to the poor developer's surprise, Python spits out a KeyError on the second loop. Add in enough lines of code to disguise it (and, in my case, some bonus recursion of dictionaries-within-dictionaries), and this turns out to be quite an awkward error to diagnose. One doesn't receive a RuntimeError, as the original `my_dict` is not modified during iteration.
It seems neither pylint or flake8 don't catch this. Is it possible to add a warning for this situation? There are somewhat similar checks already for imported variables that are redefined, or variables that are defined but then overwritten without ever being used/read.
Regards,
Daniel
Hi
I just tried installing pylint on a raspberry PI with 'pip install pylint' I
also tried 'sudo pip install pylint':
root@watercontrol:/home/pi# pip install pylint
Downloading/unpacking pylint
Downloading pylint-2.5.3.tar.gz (684kB): 684kB downloaded
Running setup.py (path:/tmp/pip-build-HIS3dh/pylint/setup.py) egg_info for
package pylint
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-build-HIS3dh/pylint/setup.py", line 63, in <module>
with open(readme_path, encoding="UTF-8") as stream:
TypeError: 'encoding' is an invalid keyword argument for this function
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip-build-HIS3dh/pylint/setup.py", line 63, in <module>
with open(readme_path, encoding="UTF-8") as stream:
TypeError: 'encoding' is an invalid keyword argument for this function
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in
/tmp/pip-build-HIS3dh/pylint
Storing debug log for failure in /root/.pip/
Pip.log is attached
Thx for any help with this!
Steve Harper
Hi all,
I wrote a small static analyser which can catch stuff like:
def foo(a, b): return a*b
foo(123) ## error: wrong number of arguments
class Foo():
def __init__(self, a):
self.a = a
def bar(self, c):
print(self.a) ## OK
return self.c ## error, because self.c never assigned
Foo() ## error: wrong number of arguments in init
You can find it here:
https://github.com/JohannesBuchner/pystrict3
and install as usual:
pip3 install pystrict3
pystrict3.py myfile.py
It further asserts a strict subset of Python, where you are not allowed
to mangle the internals nor re-assign variables.
Perhaps some can find it useful for writing more obvious code.
It can be used additional to pyflakes, pylint, flake8, etc.
Let me know any feedback, bugs, etc., and whether you think it is a
stupid or interesting idea.
Cheers,
Johannes