Underscore and meaning in Python

Posted by Afsal on 12-Aug-2022

Hello Pythonistas!

Today we will learn about the different occurrences of underscore( _ ) and it's meaning. Let us check one by one

In Python Shell

In the shell, _  means the return value of the last operation done on the python shell

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> a = 1
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> a+1
2
>>> _
2
>>>


When I enter _ for the first time there was no operation performed. So a name error raised

The second time I have assignment operator but it has no return then also a name error is raised.

But in the 3rd case, there is a return and its value is 2. After that, if we enter _ this will return 2. 

As Separator for large numbers

We can use _ as a separator for a large number. This makes code more readable

code

a = 1000000
b = 1000_000
print(a)
print(b)

output

1000000
1000000

We can see that b is more readable than a. Insertion of _ doesn't affect the value

Variable naming 

We use _ in variable names also. Based on the position of _ it has some meaning.

Name Starting with underscore

If a variable name starting with _ it means it is a protected member

eg:

Class Test:
    _name = 10

Here _the name is protected

Name start with two underscore

If a variable name starts with __ means it is a private member. 

Eg: 

Class Test:
    __name = “test”

If you need to learn more about access modifiers please click here

Name end with underscore

If a name ends with _ this means the name clash with the reserved keyword.

Eg:

is_ = “is”

Here ‘is’ is a reserved keyword. So I have used is_. This is the name conversion standard as per the pep8 rule

Name start and end with double underscores or dunders

In python, dunders are also called magic methods. In most cases we not using these methods. These are internal to python objects. Some common dunder we are using is __init__ and __str__.

These are occurrences of _ in python hope have learned something from this post. Please share your valuable feedback at afsal@parseltongue.co.in