python-2.7list-comprehensionclass-attributes

Python 2.7 list comprehension leaks variable name


I am using a list comprehension to assign a value to a class attribute in Python2.7. I noticed that this adds the variable used in the list comprehension as a class attribute.

class MyClass:
    some_strings = [s for s in ('Foo','Bar')]

print MyClass.s

Output: 'Bar' #??

Can someone explain why this is happening? Is there anything wrong with using list-comprehension there?


Solution

  • There is nothing wrong. Using a list comprehension adds its variable to the local scope, just as a for loop would. When used inside a class definition, said local scope is used to initialize the class attributes. You have to del the name s if you don't want it in your class.

    class MyClass:
      some_strings = [s for s in ('Foo','Bar')]
      del s
    

    Note that in Python 3, the list comprehension will not add its variable to the local scope.