I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.
def f(x):
return x
def main():
print f(3)
if (True):
print [f for f in [1, 2, 3]]
main()
Python 2.7.6 returns an error:
Traceback (most recent call last):
File "weird.py", line 9, in <module>
main()
File "weird.py", line 5, in main
print f(3)
UnboundLocalError: local variable 'f' referenced before assignment
Python sees the f
is used as a local variable in [f for f in [1, 2, 3]]
, and decides that it is also a local variable in f(3)
. You could add a global f
statement:
def f(x):
return x
def main():
global f
print f(3)
if (True):
print [f for f in [1, 2, 3]]
main()
It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]]
now changes the global variable f
to 3
, so it is not a function any more.
Fortunately, it works fine in Python3 after adding the parentheses to print
.