Private Variables In Python:

We should understand that in Python for Data Science, ‘Private’ instance variable does not exist, except inside an object. But most Python codes and coders have started a convention where a name is preceded by an underscore ( _), e.g., _PST. Wherever such underscore is present, it should be treated as non-public part of API or any other python code, regardless of it being a function, method or data member. We should also understand the forms of trailing underscores.

Mangling and it’s functioning:

Mangling in python means limited support for a valid use-case for class-private members. This is usually done to avoid name clashes of names where sub-classes define names. Any mark with the form __PST, i.e., two leading underscores or at most one trailing underscore, is replaced by _classname__PST, here classname is the current class name whose underscore has been stripped off.  Until it takes place within the class, mangling can be done. It becomes useful in cases where we need to let subclasses override methods but not breaking intraclass methods call.

python code data science

Mangling rules help in avoiding accidents. But we can always access and modify variables that are considered private. This can be useful in some special cases such as in debugger.

_Single Leading Underscore:

This denotes that if there is a single underscore at the beginning of a function, method or data member it means it should not be accessed as it is not a part of API.

The above snippet is from the Django source code (django/forms/forms.py). From the above snippet, it is clear that errors is part of API and also a property of it. But the method _get_errors is not the property of API. It is private, so, access is not granted.

__Double Leading Scores:

It is most confusing to have two underscores at the starting. It is all about syntax and not about the convention. Double underscore is used for mangling the attribute names of a class. This helps in avoiding conflicts of attribute names amongst classes.

__Double Leading and Double Trailing Underscores__

This is used for special variables and methods (“magic methods”) like __len__, __int__. The magic methods provide special syntactic features to the names. Some of the examples are, __file__, this indicates the location of python file, __eq__ gets executed when a == b is executed.

To learn more about private variables in python for data science, you can check this and this.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.