Given the following ...
def foo(bar):
return bar * 2
class FOO:
BAR = 2
a = foo(BAR)
class FAZ:
a = foo(BAR)
Why does python give a NameError: name 'BAR' is not defined
error? My expectation was that it would work given that foo(BAR)
is allowed and classes are allowed to refer to things outside their scope.
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 6, in <module>
class FOO:
File "foo.py", line 10, in FOO
class FAZ:
File "foo.py", line 11, in FAZ
a = foo(BAR)
NameError: name 'BAR' is not defined
Is there a technical reason for this limitation? A design one?
Is there a workaround (aside from moving BAR
outside the class)? i.e.,
BAR = 2
class FOO:
BAR = BAR
a = foo(BAR)
class FAZ:
a = foo(BAR)
Edit:
Anyone following the link to the duplicate:
At first glance, the question is somewhat different -- works in python2, not in python3 and is about list comprehensions. The accepted answer, however, seems to cover my question as well.