image block
377 Views 0 Comments
Hi guys!
Today I'm going to discuss with u the magic symbol like underscore. Why it's magical? It's a reasonable question. But what will be, if I will tell you, that this symbol has a big role on programming and in Python at all? Don't believe me? Just let's see!
And actually, I have 7 things which I hope will prove you that this symbol is useful.

7 reasons why we are using underscore in Python

1. Under underscore is saving last expression value

And what it can be, you can ask. I will explain.
The CPython interpreter is caching the last value. For example :
>>> 10
>>> _
>>> _*10
>>> _
Also it can be implemented from variable :
>>> a=10
>>> _
>>> a
>>> _
But it's just a little thing why we are using it, let's move on on the second reason.

2. Underscore is using for ignoring values

Yes, yes! You heard right!
Underscore symbol is using for ignoring not important values on our code. Let's review few examples.
Let's imagine that we need to make the cycle on our code, but we don't care about index inside of it. We can easy to do it.
>>> for _ in range(5):
...     pass
Instead the pass command we can paste any action what we need.
We can ignore values during the assignment of variables.

>>> a, _, b = (1,2,3)
>>> print (a,b)
1 3
Or ignore a lot of values (this is called "Extended Unpacking" but this function is availible from python 3.6+)
>>> a, *_, b = (1,2,3,4,5)
>>> print (a,b)
1 5

3. Underscore is using for avoiding the name conflicts

The underscore symbol in the end of variables is using for avoiding the conflict of names inside one big code.
For example, you have variable price which is using in your class, but also you need to have the same variable with which one you will work, inside some function. So, you can easily to call new variable like price_ which will have totally different space on the memory and not affect on origin one.
Now, let's move on to more reasonable things.

4. Underscore is using for making private objects

Yes, underscore at the beginning of the name of the object (variable, function, class), is telling that this object is private for the specific place.
Private, it's mean that this object will not be imported with all other elements.
For example, if I will create two files: and
In the I will call two variables :
val1 = 1
_val2 = 2
And in, I just will try to import them :
from test2 import *
And I will see, that on my I will have only varialbe val1, because _val2 variable will be ignored durring import.
This is can be implemented for any type of object.
class : class _Classname():
function : def _functionname():
variable : _variablename=0

5. The name mangling technique via underscore

At first, let's understand what is name mangling.
Name mangling is a technique used to solve problems caused by the need to resolve unique names. This technique is using on all modern programming languages and Python one from them.
In other words, if we want to restrict objects inside some class, double underscore at the beginning of name will help us. Let's see the example.
>>> class A():
...     def __init__(self):
...             self.var1 = 1
...             self._var2 = 2
...             self.__var3 = 3
>>> classA=A()
>>> dir(classA)
['_A__var3', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_var2', 'var1']
We have created the class with three variables and after calling it, printed all objects inside class.
Now we see nothing strange with first variable var1 and second one _var2. They can be use like as usual, but let's have a look on third variable __var3.
Object of this variable have a difference with other ones. From "dir" function we see, that this variable can be used only from this class and cannot be imported outside.
For example let's try to use them.
>>> classA.var1
>>> classA._var2
>>> classA.__var3
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'A' object has no attribute '__var3'
>>> classA._A__var3
That's what I'm talking about. We can use this variable only in case, when calling it from class object, like we made before.

6. Using underscore for readability

From Python 3.6, appeared additional function for underscore, which gives more comfortable usability.
I don't want to make a big attention on it, so let's review examples:
>>> dec_base=1_000_000
>>> print(dec_base) 
>>> bin_base=0b_1111_0000
>>> print(bin_base)
>>> hef_base=0x_1234_abcd
>>> print(hef_base) 

7. The underscore symbol for defining special methods

What are these methods? They're special methods that you can define to add special methods to your classes. They're always surrounded by double underscores (e.g. __init__ or __del__).
These methods have functions which are made classes more flexible and easier to use. All of them are well documented on official documentation and if you want to know more about them, you can do this by this link Python.

I I hope something from this information was a novelty and you learned something new for yourself. But today that's all from my side.

Wish you good luck!
- Kostia


    Leave a Comment