Different uses of underscore in Python

1 – Using in interpreter

When you execute the expression in the python interpreter it will store the result of last executed expression in special variable that is underscore (‘_’).

2 – Using in looping

While using loops or iterating over iterable objects you can use underscore (‘_’) as a variable.

3 – Using in digit separation

If you want to represent a long digits number, then it can be separated using underscore to make it easily readable number. It is also used to separate the parts of binary, octal or hexadecimal numbers.

4 – Using single pre underscore

Single pre underscore can be used with variable, function or method name to make them private data which means that the variables, functions defined with pre underscore cannot be imported to use publicly.

For example, first let’s create file1.py file and write the below code in it.

Now create another file file2.py and write this code to import file1.py module.

Here when you execute test2.py file it will execute the func() but prevents the execution of _func() and raises NameError as it is not defined.

5 – Using double pre underscore

It also works similar to single pre underscore, we can use double underscore as prefix with variable, function or method name to make them private data.

In addition to that it is also used to avoid the overriding of variable’s value in subclass.

6 – Using post single underscore

as we all know that we can not use reserved keywords as a variable name, but sometimes we may need to use the variable name which is already defined as reserved keyword so to avoid this naming conflict for variable names we can append the single underscore as postfix to that variable.

7 – Using double pre and post underscore

Names defined with double pre and post underscore are called magic or dunder methods in Python. We have already used this with class constructors __init__ or in __name__ == ‘__main__’.

Popular Posts

Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *