Underscore (_) in Python

16 Nov, 2021
Following are different places where _ is used in Python:
Single Underscore:In InterpreterAfter a nameBefore a nameDouble Underscore:__leading_double_underscore__before_after__
Single Underscore:In InterpreterAfter a nameBefore a name
In Interpreter
After a name
Before a name
Double Underscore:__leading_double_underscore__before_after__
__leading_double_underscore__before_after__
__leading_double_underscore
__before_after__
Single Underscore
In Interpreter:_ returns the value of last executed expression value in Python Prompt/Interpreter
>>> a = 10>>> b = 10>>> _Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name '_' is not defined>>> a+b20>>> _20>>> _ * 240>>> _40>>> _ / 220
For ignoring values:Multiple time we do not want return values at that time to assign those values to Underscore. It used as throwaway variable.
# Ignore a value of specific location/indexfor _ in range(10)    print ("Test")  # Ignore a value when unpackinga,b,_,_ = my_method(var1)
After a namePython has their by default keywords which we can not use as the variable name. To avoid such conflict between python keyword and variable we use underscore after name
Example:
>>> class MyClass():...     def __init__(self):...             print ("OWK")  >>> def my_defination(var1 = 1, class_ = MyClass):...     print (var1)...     print (class_)  >>> my_defination()1__main__.MyClass>>>
Before a nameLeading Underscore before variable/function/method name indicates to programmer that It is for internal use only, that can be modified whenever class want.
Here name prefix by underscore is treated as non-public. If specify from Import * all the name starts with _ will not import. Python does not specify truly private so this ones can be call directly from other modules if it is specified in __all__, We also call it weak Private
class Prefix:...     def __init__(self):...             self.public = 10...             self._private = 12>>> test = Prefix()>>> test.public10>>> test._private12
Python class_file.py
def public_api():    print ("public api")  def _private_api():    print ("private api")
Calling file from Prompt
>>> from class_file import *>>> public_api()public api  >>> _private_api()Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name '_private_api' is not defined  >>> import class_file>>> class_file.public_api()public api>>> class_file._private_api()private api
Double Underscore(__)
__leading_double_underscoreLeading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass.Interpreter changes variable name with class extension and that feature known as the Mangling.testFile.py
class Myclass():    def __init__(self):        self.__variable = 10
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.__variableTraceback (most recent call last):File "", line 1, inAttributeError: Myclass instance has no attribute '__variable'nce has no attribute 'Myclass'>>> obj._Myclass__variable10
In Mangling python interpreter modify variable name with ___. So Multiple time It use as the Private member because another class can not access that variable directly. Main purpose for __ is to use variable/method in class only If you want to use it outside of the class you can make public api
class Myclass():    def __init__(self):        self.__variable = 10    def func(self)        print (self.__variable)
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.func()10
__BEFORE_AFTER__Name with start with __ and ends with same considers special methods in Python. Python provides these methods to use it as the operator overloading depending on the user.
Python provides this convention to differentiate between the user-defined function with the module’s function
class Myclass():    def __add__(self,a,b):        print (a*b)
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.__add__(1,2)2>>> obj.__add__(5,2)10
This article is contributed by Nirmi Shah. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vishalsingh80
caseyfueller
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts