Underscores in Python
This post discusses the use of the
_ character in Python. Like with many things in Python, we’ll see that different usages of
_ are mostly (not always!) a matter of convention.
Single Lone Underscore (
This is typically used in 3 cases:
In the interpreter: The
_name points to the result of the last executed statement in an interactive interpreter session. This was first done by the standard CPython interpreter, and others have followed too.
>>> _ Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name '_' is not defined >>> 42 >>> _ 42 >>> 'alright!' if _ else ':(' 'alright!' >>> _ 'alright!'
As a name: This is somewhat related to the previous point.
_is used as a throw-away name. This will allow the next person reading your code to know that, by convention, a certain name is assigned but not intended to be used. For instance, you may not be
Continue reading →