BlogsDope image BlogsDope

Significance of Underscores in Python

Jan. 1, 2021 PYTHON 166

Underscores (_) hold special significance in python language. They are used in different places in python.

You might have seen underscores used in python like this before,

  • for _ in range(5):
  • _=5 
  • __init__(self) 

There are a lot more cases in which underscores are used in different ways in python.

Single Underscore(_):

1- Use in Interpreter: 

Single underscore is used to save the last executed expression in python interactive shell. Python automatically store the last expression int the variable '_'.
single underscore in Python
Here the last executed value (9) is stored in underscore (_) and we can also pass that value in a variable (a) also.

2- Ignoring the values:

Single underscore is used to ignore the specific values. If we don’t want a particular value we can simply assign it to underscore (_).
using underscore to ignore values

We can also ignore multiple values by using (*_). It is also known as External Unpacking.

using underscore to ignore values in Python
This is also known as Tuple Unpacking.

3- Use in looping:

Underscore can be used as the variable in the loop.

for _ in range(5):
    print(_)

Output:

​​0

1

2

3

4

4- Separating digits of numbers:

 Underscore can be used as the visual separator for big numbers, for better understanding.
a=1_000_000
print(a)

Output:

​1000000​

It can also be used to separate binary, octal, hexadecimal numbers.

print(0b_1000) #Binary
print(0x_21_10) #Hexa-decimal
print(0o_25) #Octal

Output:

​8

8464

21

We can also use the single underscore as the naming of variables, class and functions.

 Single Leading Underscore(_variable):

​Single leading underscore is used for internal purpose only. It can be used in variable names, class names and method names, but they are treated as “private” by the programmer.
class A:

    def __init__(self):
        self.name = "CodesDope"
        self._id=101

obj = A()
print(obj.name)
print(obj._id)

Output:

CodesDope 

101

While importing, from A import * does not import objects whose names start with an underscore.

#filename is main.py
#variable name having single leading underscore.
_a="helloworld"

def mul(x,y):
    print (x*y)
#function name having single leading underscore
def _sub(x,y):
    print (x-y)

Importing main.py to test.py

from main import *
#accessing variable names having single leading underscore.
print (_a) #Output:NameError: name '_a' is not defined


#accessing function name having single leading underscore
print (_sub(7,2)) #Output:NameError: name '_sub' is not defined


#accessing variables and functions which is not having single leading underscore, we will able to access those variables and functions
mul(3,4) #Output:12

If we want to import variables and functions having a single leading underscore, we have to mention the name while importing.

from main import _a,_sub
	
#accessing variable names having single leading underscore.
print (_a)

#accessing function name having single leading underscore
_sub(7,2)

Output:

​helloworld

5

Single trailing underscore(variable_):

Single trailing underscores are used to resolve the conflict with python keywords. If we want to use Python Keywords as a variable, function or class names, we can simply add an underscore to it.
For example: Rather than using list we can use list_ as the name of variable.
list=[1,2,3]
t=(5,6,7)

#Coverting tuple to list using list() constructor
t1=list(t)

Output:

TypeError: 'list' object is not callable

We can resolve it by using list_

list_=[1,2,3]
t=(5,6,7)

#Coverting tuple to list using list() constructor
t1=list(t)
print (t1)

Output:

[5, 6, 7]

Double Pre Underscore (__variable):

Double pre underscore is used for Mangling
Name Mangling: interpreter of the Python alters the variable name in a way that it is challenging to clash when the class is inherited. 
Double leading underscore tells the Python interpreter to rewrite the attributes names and method names of subclasses to avoid naming conflicts.
self._className__methodname() instead of self.__methodname() 
self._classname__attributename instead of self.__attributename 
class A:
    def __init__(self,name,id):
        self.name=name
        self.__id=id

a=A("CodesDope",101)

print (a.name)
print (a.__id

Output:

​CodesDope

print (a.__id) 

AttributeError: 'A' object has no attribute '__id' 

To resolve this problem we have to write:

class A:
    def __init__(self,name,id):
        self.name=name
        self.__id=id

a=A("CodesDope",101)

print (a.name)
print (a._A__id) //Name Mangling

Output:

​CodesDope 

101

Double leading and trailing underscore (__variable__):​

​Special methods or magic methods in python are named with double leading and trailing underscore. Thesse kind ofmethoods are also called dunder methods. 
 For example, __add__(), __mul__() , __init__(self) 
class A():

    def __init__(self):
        self.__num__ = 101

a= A()
a.__num__

Output:

​101


Yeah we did it!

Now you can move to next chapter.

Learn the Python Programming Language and strengthen your grip on the subject. 


Liked the post?
Editor's Picks
0 COMMENT

Please login to view or add comment(s).