Consider this code:
def gee(bool_, int32, int64, str_):
class S:
bool_ = bool_
int32 = int32
int64 = int64
str_ = str_
return S
gee(1, 2, 3, 4)
Running this gives an error:
Traceback (most recent call last):
File "test_.py", line 36, in <module>
gee(1, 2, 3, 4)
File "test_.py", line 27, in gee
class S:
File "test_.py", line 28, in S
bool_ = bool_
NameError: name 'bool_' is not defined
I have no idea which scope/closure rules apply here. nonlocal
fixes the error but the result is not what I've expected:
def gee(bool_, int32, int64, str_):
class S:
nonlocal bool_, int32, int64, str_
bool_ = None
int32 = None
int64 = None
str_ = None
print(bool_, int32, int64, str_ )
return S
g = gee(1, 2, 3, 4)
g.bool_
Outputs:
None None None None
Traceback (most recent call last):
File "test_.py", line 38, in <module>
g.bool_
AttributeError: type object 'S' has no attribute 'bool_'
Beside rename what can I do to make assignments in 1st code snippet work? And why it behaves like that? Because there is name = ...
? Why Python doesn't evaluate the name before assignment?