Underscores in Python have four special usage scenarios. Some of them are conventions to improve readability of code. Some of them have special functions we must know. The four scenarios are:
This post will talk about all of them to help you totally understand how to use underscores in Python.
Sometimes, if a number is too long, it’s hard and boring to count how many digits this number has. For example, if there is a variable a=1000000000000, how many zeros in a?
Fortunately, Python gives us a very simple way to use underscores as visual separators for digit grouping purposes in integral, floating-point and complex number literals. If we need to define a long number, don’t forget to use underscores to make life easier.
>>> a = 1_000_000_000_000>>> a1000000000000
The above statement of a=1_000_000_000_000 is totally the same as a=1000000000000 . Which way do you like to define the a ? ????
Sometimes, a part of values of a container(list/tuple and so on) are useless. We can use an underscore to ignore them.
>>> L = [1,3,5,7]>>> a, _, b, _ = L>>> print(a, b)1 5
As the above code shown, we need to get the first and third values of L and assign them to variables a and b. In the meanwhile, the second and last values are useless. We just use _ to ignore them.
Note: This usage scenario is just a convention. We can use any other names to do this. But using underscore is best choice to avoid ambiguity and let other developers understand it easily.
This is an interesting and small trick of Python Interpreter. We can use one underscore to simply get the last expression’s value.
>>> 5+611>>> _11
Underscores are often used in variable,class and function names. For example:
first_name = 'Yang'
When we define the variable first_name , we used a _ to make it more readable.
Besides using underscores in the middle position of a name, there are four special naming patterns we should know:
In object-oriented programming, there are three types of class members:
class Student: def __init__(self, name, age, grade): self.name = name # public member self._age = age # protected member self.__grade = grade # private member
There are two tips about leading underscores:
Sometimes, we think of a good name for a variable, but unfortunately, the name conflicts with Python keywords or built-ins. We can just use a single trailing underscore to avoid ambiguity. For example:
>>> list_ = [1,2,3] # good naming style>>> list = [2,3,4] # bad name; has ambiguity with Python keyword
This convention is used for special variables or methods (so-called “magic method”) of a Python class, such as __init__() method. We just need to know that this convention is used for Python magic methods and avoid naming our variables or methods like this.
A good developer should follow common code conventions and pay attention to details. Using underscores properly in Python is a good habit.
Thanks for reading.