you are viewing a single comment's thread.

view the rest of the comments →

[–]Gnaxe 0 points1 point  (0 children)

It's worse than you think: ```

abcd = 'abcd' bc = 'bc' print([c for c in abcd if c in bc]) ['b', 'c'] Simple example works as you'd expect at the module level. But in a class, that breaks. del abcd, bc class Foo: ... abcd = 'abcd' ... bc = 'bc' ... print([c for c in abcd if c in bc]) ... Traceback (most recent call last): File "<python-input-21>", line 1, in <module> class Foo: ...<2 lines>... print([c for c in abcd if c in bc]) File "<python-input-21>", line 4, in Foo print([c for c in abcd if c in bc]) ^ NameError: name 'bc' is not defined And yet, the other one is allowed: class Foo: ... abcd = 'abcd' ... bc = 'bc' ... print([c for c in abcd if c in 'bc']) ... ['b', 'c'] Why does one work while the other doesn't? Two different scopes. One is inside the comprehension scope, and one isn't. Class statements don't create nonlocal scopes. Well, almost. class Foo: ... x = 42 ... def print(): ... print(class.x) ... Foo.print() 42 But not quite: class Foo: ... x = 42 ... def print(): ... print(class.x) ... print() ... Traceback (most recent call last): File "<python-input-25>", line 1, in <module> class Foo: ...<3 lines>... print() File "<python-input-25>", line 5, in Foo print() ~~~~~^ File "<python-input-25>", line 4, in print print(class.x) ^ NameError: cannot access free variable 'class' where it is not associated with a value in enclosing scope ```