What is the meaning of single underscore prefix with Python variables?

PythonServer Side ProgrammingProgramming

Python variable name may begin with a single underscore. It functions as a convention to indicate that the variable name is now a private variable. It should be viewed as an implementation detail that could change at any time. Programmers can assume that variables marked with a single underscore are reserved for internal usage.

Single underscores are advised for semi-private variables, and double underscores are advised for fully private variables.

To paraphrase PEP-8; single leading underscore: a poor signal of "internal use." For instance, from M import * excludes objects with names that begin with an underscore.


The syntax used for the single pre underscore with Python variables is as follows −


Example 1

The buzz variable is made private in the example below by adding a single underscore before it. This approach still permits access to the _buzz variable when we instantiate an object of this class and try to access the _buzz variable. It is referred to as a "weak private indication" for this reason.

class Python: def __init__(self): self.fee = 37 self._buzz = 76 object = Python() print(object.fee) print(object._buzz)


Following is an output of the above code −


Example 2

Following is an example of single leading underscore (_v):

class Sports: def __init__(self): self.name = 'Cricket' self._player = 'Sachin Tendulkar'


Following is an output of the above code where we tried to access the ‘name’ and ‘player −

>>> s = Sports()
>>> s.name
>>> s._player
'Sachin Tendulkar'

Note − Accessing the single pre underscore variable is not prevented by single pre underscore.However, a single pre underscore has an impact on the names imported from the module.

Example 3

Written the following code in untitled.py file

# The file name is ‘untitled.py’ def function(): return "programming" def _private_function(): return 35


Python doesn't import names that begin with a single pre-underscore if you import all the methods and names from untitled.py.

Following is an output of the above code −

>>> from untitled import *
>>> function()
>>> _private_function()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_private_function' is not defined

The modules should be imported normally to avoid the above error −

>>> import untitled
>>> untitled.function()
>>> untitled._private_function()

Note − Single Pre Underscore is solely meant for internal use.


The difference between double and single underscore prefixes is demonstrated in the following code.

class Python(): def __init__(self): self.__FullPrivate = "Coding" self._SemiPrivate = "Programs" p = Python() print ('p._SemiPrivate') print ('p.__FullPrivate')


Following is an output of the above code −

Updated on 23-Nov-2022 08:33:34