I got stuck by some weird behavior in Python 3.5.2. I have a class Foo and want to execute a piece of code only once for all instances. This code is placed directly below the class statement.
import os
class Foo:
    path = "annotations/"
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
    def __init__(self, x):
        # do something
        1+1
When runing this code, the following error message appears if the annotations directory is not empty (an empty file suffices)
Traceback (most recent call last):
    File "foo.py", line 3, in <module>
    class Foo:   File "foo.py", line 6, in Foo
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]   File "foo.py", line 6, in <listcomp>
    files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
NameError: name 'path' is not defined
However, no error occurs if the annotations/ is empty. Why? This strange behavior only occurs when using the single-line for loop.
I use Python 3.5.2. When running the above code with Python 2.7.12, the error does not appear.
 
     
    