I've run into a strange case in my Python code, and I'm trying to figure out why this occurs.
rounds = 10
probability = 100
items = [1, 2, 3, 4, 5]
from numpy.random import uniform
for r in range(1, rounds):
sample = {item: uniform() < probability for item in items}
When I run the above code, I get the following NameError:
File "sample.py", line 6, in <module>
sample = {item: uniform() < probability for item in items}
File "sample.py", line 6, in <dictcomp>
sample = {item: uniform() < probability for item in items}
NameError: name 'uniform' is not defined
This is very strange, since I am importing uniform directly before using it in the following line. I got the same error using the random
module. I'm using other packages in my code (including argparse
and pickle
) but only the random number generation is giving me errors. I'm running Python 3 on a Windows machine. I also get the same error when I move the import
statement inside the for
loop.
rounds = 10
probability = 100
items = [1, 2, 3, 4, 5]
for r in range(1, rounds):
from numpy.random import uniform
sample = {item: uniform() < probability for item in items}
What could be causing this error?
EDIT: I encountered another interesting phenomenon. The below code blocks are giving the same NameError
for uniform
.
from numpy.random import uniform
sample = {item: uniform() for item in [1,2,3]}
... and ...
from numpy.random import uniform
sample = [uniform() for item in [1,2,3]]
However, the following code does NOT give a NameError
for uniform
.
from numpy.random import uniform
sample = {1: uniform(), 2: uniform(), 3: uniform()}
There seems to be something in the way Python handles dictionary/list comprehensions that makes the first two code blocks illegal but the third one okay.