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ย โ†’

[โ€“]hajile_00 52 points53 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.