I don't like this behavior, but this is how Python works. There were other answers to the question, but for completeness, let me point out that Python 2 has more of 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 that f 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 can 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 works; 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 no longer a function.
Fortunately, it works great in Python3 after adding parentheses to print .
osa Oct 27 '14 at 1:10 2014-10-27 01:10
source share