Python Name Mangling and How to Use Underscores

Why __var in python probably doesn’t work the way you think it does

Andrew Scott
Analytics Vidhya
Published in
4 min readJan 26, 2020

--

Based on photo by David Clode on Unsplash

_single underscore prefix

If you’re using any underscores in your code, you’re most likely using these. Single leading underscores are used as a weak “internal use” or “private” indicator for methods and data attributes. These objects are still totally accessible outside of their parent class at runtime, so it’s really more of a gentleman’s agreement not to use them as modification of these objects could have unanticipated consequences — though I did have a coworker mention that when he was a more junior engineer, one of his teammate threatened to break his thumbs if he caught him accessing _private variables. The single-underscore variable naming convention was established in Pep-8.

A common use case where I like to use single underscore variables is on classes where I have some attributes which are a calculated value and want to discourage direct modification. See the following example.

One final point about single leading underscores is that they while they don’t impact the user’s ability to access the objects, they do impact how what is included when a module is imported — as _private objects are not included in from x import * style import statements.

If we have a module with the following we can see this behavior when we try to import and access a _private method in the REPL.

>>> from foo import *
>>> public_method()
I'm public
>>> _private_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_private_method' is not defined

__double underscore prefix

--

--

Andrew Scott
Analytics Vidhya

Maintainer @OchronaSec | PANW, ex Expanse, ex Tenable | Security & Automation | All views are my own... and awesome