February 12, 2022
Python Underscores Part 3
Double leading and trailing underscores
__var__
When dealing with classes in Python, you're going to meet with these types of underscores a lot.
Interestingly, this typing is not affected by the interpreter but there're "magic methods" which reserve the use of those.
Examples:
__init__ <- for object constructors __call__ <- for making objects callable __str__ <- for returning concise textual representation of an instance ...and many more
Since we have these methods with their corresponding names, we shouldn't use the double leading and trailing underscores when naming our variables.
Single underscores
_
For creating an insignificant(don't care) or a temporary variable that can be used in unpacking and other cases.
Ok, let's look at a simple example
Example:
student = ('Tom', 'Garfield', 18, 'CS') name, _, _, course = student print(name) #Tom print(course) #CS print(_) #18
Ready for something amazing?
In Python REPLs, single underscore is considered "special" and that represents the result of the last expression by the interpreter.
Example:
>>> 10 + 6 16 >>> _ 16 >>> print(_) 16
It is also possible to create objects on the fly and play with them without naming them first.
Example:
>>> list() [] >>> _.append(1) >>> _.append(2) >>> _.append(3) >>> _ [1, 2, 3] >>> _[1] 2
All of these could be a little difficult to get but after some rerepetitions, you would see how wonderful these can be.