4 ms·
The cited claim about python mangling dunders is 100% not my experience > If a class member starts with two leading underscores, then it really is private. The
by mdaniel 1y ago
The cited claim about python mangling dunders is 100% not my experience
> If a class member starts with two leading underscores, then it really is private. The language will name mangle it to make it inaccessible.
$ cat > jimbo.py <<PY
__to_whom__ = "world"
def __hello():
return __to_whom__
PY
python3 -c '
import jimbo
print(dir(jimbo))
print(jimbo.__to_whom__)
'
['__builtins__', '__cached__', '__doc__', '__file__', '__hello', '__loader__', '__name__', '__package__', '__spec__', '__to_whom__']
world
and, just on the off chance they really meant "class member" I tried that, too
$ cat jimbo.py; python3 -c 'import jimbo
print(dir(jimbo.s))
print(jimbo.s.__to_whom__)
'
class Sekrit:
__to_whom__ = "world"
def __hello(self):
return self.__to_whom__
s = Sekrit()
['_Sekrit__hello', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__to_whom__', '__weakref__']
world
- rnice 1y agoOnly names which start with double underscores AND do not end with double underscores.
- mdaniel 1y agoDoesn't the "__hello" def qualify for your description? It shows up in both dir() outputs, although admittedly it is "name mangled" with the outer class name, so maybe that's what they meant I guess this could qualify for a TIL because I didn't know Python treated leading and trailing dunders any different and that they were its implementation of "protected" and "private" only by convention
- arjvik 1y agoThe name mangling is what is being referred to. Specifically, you can access it as Sekrit()._Sekrit__hello(), but that's a pretty obvious boundary-break compared to .__hello(). Members ending in a double underscore as well aren't mangled, because this interferes with syntax sugar methods like __add__ (addition operator overloading).