I get NameError: name 'ID' is not defined when trying to access the class variable in a dict comprehension e.g. in class A. When referencing without a comprehension it works fine (see class B). So my question is, why does it throw a NameError in class A but not in class B?
class A:
ID = "This is class A."
test = {str(i): ID for i in range(5)}
class B:
ID = "This is class B."
test = f"{ID}"
Class definition blocks and arguments to
exec()andeval()are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail.
You have declared a variable ID inside the class definition that makes it an class or static variable. So its scope is limited the to class block, and hence you can't access it inside the comprehensions.
you can read more about it at python docs
Consider the examples,
Example #1:
class A:
ID = "This is class A."
print(ID)
Now when you execute >>>A() the output will be This is class A which is totally fine because the scope of variable ID is limited to class A
Example #2:
class B:
L = [ 1, 2, 3, 4, 5, 6, 7]
print([i * 2 for i in L])
Now when you execute >>>B() the output will be [2, 4, 6, 8, 10, 12, 14] which is totally fine because the scope of list L is limited to class B
Example #3:
class C:
L = [ 1, 2, 3, 4, 5, 6, 7]
print([L[i] * 2 for i in range(7)])
Now executing >>>C() will raise a NameError stating that name L is not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With