I'm trying understand python scope rules. To do this I try access "very private" variable from class in same module
bar = "bar"
_bar = "underscore"
__bar = "double underscore"
def foo():
print bar
print _bar
print globals()["__bar"]
print __bar
class Foo:
def __init__(self):
print bar
print _bar
print globals()["__bar"]
print __bar #NameError: global name '_Foo__bar' is not defined
foo()
Foo()
It fails with NameError
. I can't find anything about that in specification. So, why it fails and where this behavior described?
Within a class definition, all names starting with double underscores are mangled; rewritten to include the class name as a prefix.
This is a feature to support marking names as 'private' within the class and protect it against being overwritten by subclasses. See the identifiers documentation:
Best not use double-underscore prefixes on module globals; there is no need to do so, a single underscore is enough to communicate that the value is internal to the module.
If you are stuck with such a value, create an alias that isn't mangled, or use
globals()[name]
.