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

--

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.

--

--

Andrew Scott
Analytics Vidhya

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