The Special Meaning of Underscores in Python

Different ways to use underscores

Photo by The Lazy Artist Gallery from Pexels

Underscores in Python

Underscores have a special meaning in Python. They’re used in different places in Python.

Following are the different types of underscores used in Python:

 

Image Source: Author

1. Single Underscore

Saving the value of the last executed expression

A single underscore is used for saving the value of the last executed expression in the Python interactive command prompt. We can also save the value to another variable.

 

Single underscore used in Python interactive command prompt

Ignoring values in looping

A single underscore _ in Python is used for ignoring some values. If we don’t want to use some values, we can assign values to _.

https://gist.github.com/IndhumathyChelliah/7339795b7981117315f55833bf6226a5

Ignoring values in tuple unpacking

If we want to ignore some values while tuple unpacking, we can assign those values to _.

https://gist.github.com/IndhumathyChelliah/bea922187675be13e5ccf0966dc70dbc

Used in numeric literals

Underscores can be used as visual separators for digit grouping purposes in integral, floating-point, and complex number literals. The underscores have no semantic meaning, and literals are parsed as if the underscores were absent.

https://gist.github.com/IndhumathyChelliah/cd8d6672bed351417da813e65b347cad


2.Single Leading Underscore

A single leading underscore can be used in variable names, method names, and class names. It indicates that those variables, methods, and class names with a single leading underscore are treated as “private” by the programmer. If we specify from M import * , those names starting with a single leading underscore are not imported. If we want to import those variables/methods, we have to specify the name while importing.

To quote PEP-8

“_single_leading_underscore: weak “internal use” indicator.
 E.g. from M import * does not import objects whose names start with an underscore.”

https://gist.github.com/IndhumathyChelliah/a978189105bde58b2576cd704931df17

Importing the above-mentioned Python file c1.py to c2.py

Example: from c1 import *

Variables and functions which have a single leading underscore cannot be accessed.

https://gist.github.com/IndhumathyChelliah/f1f281dee705fd6552845a8c9b755c96

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

Example: from c1 import _a,_sub

https://gist.github.com/IndhumathyChelliah/add582d8e2ab55ce676bb2c0179a8bcb


3. Single Trailing Underscore

Single trailing underscores are used to avoid conflicts with Python keywords.

To quote PEP-8:

“single_trailing_underscore_: used by convention to avoid conflicts with Python keyword”

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

In the above example, we can use list_ as the variable name to avoid a conflict with the Python keyword 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]

4. Double Leading Underscore

Double leading underscore tells the Python interpreter to rewrite the attributes names and method names of subclasses to avoid naming conflicts. Interpreter changing attribute names with class extension is known as name mangling.

self._className__methodname() instead of self.__methodname()

self._classname__attributename instead of self.__attributename

As per Python documentation:

“Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.”

To quote PEP-8:

“__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo)”

https://gist.github.com/IndhumathyChelliah/0531276d7a60453fa9afef5d0575dd40

The inherited class having the same method name:

https://gist.github.com/IndhumathyChelliah/a14a0fc29897a4806f1d473bb013b68e


5. Double Leading and a Double Trailing Underscore

Special methods in Python are named with double leading and double trailing underscores. They are known as magic methods/dunder methods in Python.

Example: __init__,__str__,__repr__,__len__. These magic methods have special meaning in Python. We can override those to change our class’ behavior.

To quote PEP-8

__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.”

As per Python convention, avoid using variable name having double leading and double trailing underscore.

We can use the dir() function to see the magic methods inherited by the class.

https://gist.github.com/IndhumathyChelliah/285048e24faf4a3dcda102703daf971c


Resources

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s