Content:
The concept of variable visibility is common in many programming languages. Making an attribute private can be used to prevent the alteration of a variable from outside of its class.
Python, however, has no such functionality. Variable visibility simply doesn’t exist, with all variables being considered ‘public’. Whatever you do, you can’t grammatically prevent a class variable being modified externally.
There is, though, a convention which most Python programmers follow. Prefixing your class variable with an underscore signals that the variable should be treated as though it were private.
It’s important to learn this convention, for a couple of reasons.
When reading code written by other programmers, you’ll likely come across names prefixed with an underscore. Naming schemes are often project-specific, and don’t necessarily have any meaning behind them. The underscore prefix does have meaning, and you should be able to recognise this when reading Python code.
You should also understand that ‘private’ class variables (or indeed, other elements of a code base which may be similarly prefixed) are subject to change without warning. They can be considered part of an internal private API, which users should not rely on. If you’re incorporating and extending a third-party module in your code, be sure to tread carefully around underscore-prefixed class variables.