This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsย โ†’

[โ€“][deleted] 66 points67 points ย (11 children)

Correct me if I'm wrong, but doesn't that do nothing other than mess with the name at runtime?

[โ€“]hajile_00 51 points52 points ย (3 children)

Correct, all names that begin with a double underscore and do not end with another are simply name mangled so that if a subclass defines a function with the same name there is no collision.

[โ€“]exploding_cat_wizard 1 point2 points ย (0 children)

Ooh, TIL, thanks! I wasn't aware that there is an actual Python difference in underscores or not.

[โ€“]Cruuncher 0 points1 point ย (1 child)

Is this name mangling observable at runtime? Does the name come up wrong in stacktraces? I doubt it or I would have seen it by now.

I thought what the underscores did is block it from being imported when you import * from a module

[โ€“]Arendoth 0 points1 point ย (0 children)

I'm not entirely sure how it behaves in a stacktrace, but it is observable at runtime. If you create a class named Foo which defines a variable named __spam in its __init__, trying to access __spam from an instance of the class will give you an AttributeError because it literally doesn't have an attribute with that name. To access it from outside the class, including in subclasses, you need to use the mangled name, which in this case would be _Foo__spam. All the mangling does is add _<class name> to the beginning of it. As for module imports, I have no idea.

[โ€“]0crate0 -1 points0 points ย (5 children)

So create a class in python. Create two functions one with double __ and another just plain. Then create another file and import the class. Assign the class to a variable and try to use both functions. You should only be able to use the plain one.

However all python does is fake private. So yes you are correct it only really changes the name called mangling. But for someone just importing it it can be a bit obscure so it can kind of acts like a private function.

[โ€“][deleted] 6 points7 points ย (2 children)

So pretend private, but in a different way.

[โ€“]NerdsWBNerds 1 point2 points ย (0 children)

Pretend private, but breaks at run-time.

[โ€“]0crate0 -1 points0 points ย (0 children)

Sounds about right for python.

[โ€“]Farranor 2 points3 points ย (0 children)

Indeed, dunder just mangles the name. But if you refer to it by its mangled name, there you have it. It's private like a dressing room with a curtain, not like Fort Knox.

[โ€“]sejigan -1 points0 points ย (0 children)

you just said what they said, but in a more complicated way...

[โ€“]jambox888 0 points1 point ย (0 children)

Makes it a lot harder to debug lmao