Name Mangling — ELI5

Imagine you and your sibling both keep a diary. You both call it “My Diary.” One day your sibling accidentally opens your diary thinking it’s theirs. Oops.

Now imagine your mom puts a label on each diary: “Alex’s Diary” and “Sam’s Diary.” They’re still in the same room, but now nobody grabs the wrong one.

That’s name mangling in Python. When you name something with two underscores at the front (like __secret), Python quietly renames it behind the scenes by sticking the class name in front. So __secret in a class called Dog becomes _Dog__secret.

Why Bother?

Python doesn’t really have private variables like some other languages. Everything is accessible if you know where to look. Name mangling is Python’s gentle way of saying: “This is meant to be internal. I won’t stop you from accessing it, but I’ll make it awkward enough that you’ll think twice.”

The real purpose isn’t security — it’s preventing accidental name collisions. If a parent class and a child class both have an attribute called __count, name mangling makes sure they don’t step on each other. The parent’s becomes _Parent__count and the child’s becomes _Child__count.

The Shortcut

  • One underscore (_private): “Please don’t touch this” — a polite convention.
  • Two underscores (__mangled): Python actually renames it — a stronger hint.
  • Two underscores on both sides (__init__): That’s a special Python method, not name mangling.

One thing to remember: Name mangling is Python’s way of adding a class-name label to attributes that start with double underscores, preventing parent and child classes from accidentally using the same name.

pythonadvancedoop

See Also