Note that what I'm after here is deeper understanding of how python works. I am aware that I can use methods or @property
and that any practical needs here would be esoteric and odd.
It is my understanding that when a class is initialized in python, its body is executed within a new namespace, then the locals of that namespace are copied into the class definition.
That said, something odd is happening with comprehensions.
class Foo:
a = (1,2,3)
b = [2*x for x in a]
This works fine as expected. No errors.
But simply adding an if
clause that references a
class Foo:
a = (1,2,3)
b = [2*x for x in (2,3,4) if x in a]
Results in
Input In [3], in <listcomp>(.0)
1 class Foo:
2 a = (1,2,3)
----> 3 b = [2*x for x in (2,3,4) if x in a]
NameError: name 'a' is not defined
Confusing since a
is accessible inside the comprehension. Though I suppose there's a difference between specifying what is being iterated and what happens on an iteration.
But even more confusing, this works fine.
class Foo:
a = (1,2,3)
b = []
for x in (2,3,4):
if x in a:
b.append(x)
So what is going on? What is the comprehension doing that a
was not accessible? I always thought it just expanded into something of this sort but clearly that's not the case.