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 do some functions have underscores __ before and after the function name?
From the Python PEP 8 -- Style Guide for Python Code:
Descriptive: Naming Styles
The following special forms using leading or trailing underscores are
recognized (these can generally be combined with any case convention):
_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, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside class FooBar,__boo
becomes_FooBar__boo
; see below).
__double_leading_and_trailing_underscore__
: "magic" objects or attributes that live in user-controlled namespaces. E.g.__init__
,
__import__
or__file__
. Never invent such names; only use them as documented.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
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.
Python _ meaning when assigned after for loop
_
is just used as a placeholder for a discarded variable.
Let's assume there is a function which returns a tuple with two elements, and I am interested only in the second part of the tuple, then it is a general practice to use _
for the variable I do not need.
e.g.
>>> def return_tuple():
... return (24,7)
...
>>> _, days = return_tuple()
>>> days
7
What is the meaning of 'for _ in range()
When you are not interested in some values returned by a function we use underscore in place of variable name . Basically it means you are not interested in how many times the loop is run till now just that it should run some specific number of times overall.
Why do we use _ in variable names?
It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:
class Foo
{
private int _counter;
public int GetCounter()
{
return _counter;
}
public int SetCounter(int counter)
{
_counter = counter;
}
}
Related Topics
Is There Go Up Line Character? (Opposite of \N)
Why Is Reading Lines from Stdin Much Slower in C++ Than Python
How to Terminate Process from Python Using Pid
Force Python to Use an Older Version of Module (Than What I Have Installed Now)
How to Upgrade Python Version to 3.7
How to Iterate Through Two Lists in Parallel
How to Serve Static Files in Flask
Syntax Error on Print With Python 3
How to Make a Sprite Move When Key Is Held Down
Error "Microsoft Visual C++ 14.0 Is Required (Unable to Find Vcvarsall.Bat)"
Why Dict.Get(Key) Instead of Dict[Key]
How to Import a Module Given Its Name as String
How Are Iloc and Loc Different
Cartesian Product of X and Y Array Points into Single Array of 2D Points