What is the purpose of the single underscore _ variable in Python?
_
has 3 main conventional uses in Python:
To hold the result of the last executed expression in an interactive
interpreter session (see docs). This precedent was set by the standard CPython
interpreter, and other interpreters have followed suitFor translation lookup in i18n (see the
gettext
documentation for example), as in code likeraise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name:
To indicate that part
of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:label, has_label, _ = text.partition(':')
As part of a function definition (using either
def
orlambda
), where
the signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like:def callback(_):
return True[For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]
This use case can conflict with the translation lookup use case, so it is necessary to avoid using
_
as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore,__
, as their throwaway variable for exactly this reason).Linters often recognize this use case. For example
year, month, day = date()
will raise a lint warning ifday
is not used later in the code. The fix, ifday
is truly not needed, is to writeyear, month, _ = date()
. Same with lambda functions,lambda arg: 1.0
creates a function requiring one argument but not using it, which will be caught by lint. The fix is to writelambda _: 1.0
. An unused variable is often hiding a bug/typo (e.g. setday
but usedya
in the next line).The pattern matching feature added in Python 3.10 elevated this usage from "convention" to "language syntax" where
match
statements are concerned: in match cases,_
is a wildcard pattern, and the runtime doesn't even bind a value to the symbol in that case.For other use cases, remember that
_
is still a valid variable name, and hence will still keep objects alive. In cases where this is undesirable (e.g. to release memory or external resources) an explicitdel name
call will both satisfy linters that the name is being used, and promptly clear the reference to the object.
What is the meaning of single and double underscore before an object name?
Single Underscore
In a class, names with a leading underscore indicate to other programmers that the attribute or method is intended to be be used inside that class. However, privacy is not enforced in any way.
Using leading underscores for functions in a module indicates it should not be imported from somewhere else.
From the PEP-8 style guide:
_single_leading_underscore
: weak "internal use" indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
Double Underscore (Name Mangling)
From the Python docs:
Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, whereclassname
is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
And a warning from the same page:
Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.
Example
>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
Why use underscore ( '_') as a variable name?
When unpacking lists/tuples, _
is typically used for values you won't need later. If you look closely at that code, the _
variable isn't actually used anywhere.
Note that in the Python REPL, _
refers to the latest result.
>>> 2+2
4
>>> _
4
Does underscore character in python variable names matter to the interpreter?
Single Leading Underscore: _var
The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.Single Trailing Underscore: var_
Sometimes the most fitting name for a variable is already taken by a keyword. Therefore names like class or def cannot be used as variable names in Python. In this case you can append a single underscore to break the naming conflict.Double Leading Underscore: __var
With Python class attributes (variables and methods) that start with double underscores, things are a little different.
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.
This is also called name mangling—the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.Double Leading and Trailing Underscore: var
Perhaps surprisingly, name mangling is not applied if a name starts and ends with double underscores. Variables surrounded by a double underscore prefix and postfix are left unscathed by the Python interpeter.
These paragraphs are taken from https://dbader.org/. Please check the page for more detailed information and examples.
Underscore after a variable name in Python
No semantics are associated with a trailing underscore. According to PEP 8
, the style guide for Python, users are urged to use trailing underscores in order to not conflict with Python keywords and/or Python built-ins:
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
Using set_
means that the built-in name for sets, i.e set
, won't get shadowed and lose its known reference during the function call.
Python leading underscore _variables
It is a naming convention for private variables. See 9.6, private variables: http://docs.python.org/tutorial/classes.html#private-variables
Underscore _ as variable name in Python
Yep, _
is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
you might code
s = min((s for s in squares if len(values[s])>1),
key=lambda s: len(values[s]))
(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key=
optional parameter is generally the best way to do DSU;-).
using underscore for a variable as same as keyword name in python
As stated in https://pep8.org/#function-and-method-arguments
If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus
class_
is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
Note that a prefix underscore e.g. _class
usually implies a private class attribute or method, something like:
class MyClass:
def __init__(self):
self._my_private_variable = 1
def _my_private_method(self):
pass
Some further info in https://pep8.org/#descriptive-naming-styles
_single_leading_underscore
: weak “internal use” indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts
with Python keyword
Underscore variable with walrus operator in Python
You are using the variable dummy
, to filter the series. Therefore, don't replace it with _
.
Related Topics
Split a Python List into Other "Sublists" I.E Smaller Lists
Python Nested Functions Variable Scoping
What Does a for Loop Within a List Do in Python
How to Replace Two Things at Once in a String
How to Color Python Logging Output
Doing Something Before Program Exit
"Line Contains Null Byte" in CSV Reader (Python)
Reversing a Regular Expression in Python
Python: Source Code String Cannot Contain Null Bytes
Usage of Sys.Stdout.Flush() Method
Numpy Index Slice Without Losing Dimension Information
Get Fully Qualified Class Name of an Object in Python
Increment a Python Floating Point Value by the Smallest Possible Amount
What Do the Python File Extensions, .Pyc .Pyd .Pyo Stand For