What does _ do in Python?

I have seen a symbol _

used in Python somewhere , for example:

print _

      

Can someone help me explain what it does?

+3


source to share


3 answers


In the interactive interpreter, it _

always refers to the last output value:

>>> 1 + 1
2
>>> print _
2
>>> 2 + 2
4
>>> print _
4
>>>

      

However, in normal Python code, 1_

is a typical name. You can assign it like any other:

_ = 3
print _
# Output: 3

      

Although I would not recommend doing this, because it _

's a terrible name. Also, it is conventionally used as a name, which is just a placeholder. An example would be:

a, _, b = [1, 2, 3]

      

which is used _

to denote what we are not interested in 2

. Another example:



for _ in range(10):
    function()

      

which means we don't use the counter variable inside the loop. Instead, we want Python to call function

ten times and need to in _

order to have valid syntax.


1 By "Python" I mean CPython, which is the standard flavor of the language. Other implementations can do different things. IPython, for example, has this to say about underscore names:

The following GLOBAL variables always exist (so don't overwrite them):

[_] (a single underscore) : stores previous output, like Python’s default interpreter.
[__] (two underscores): next previous.
[___] (three underscores): next-next previous.

      

Source: http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system

+16


source


It's just a different variable name that is commonly used for three very different things:

In the Python interactive shell, _ is the value of the last expression entered:

>>> 3 + 3
6
>>> _ == 6
True

      

It is used to indicate that a variable only exists because it should and will not be used:



instance, _ = models.MyModel.objects.get_or_create(name="Whee")

      

(here get_or_create returns a tuple with two elements, only one of which goes for us to use).

The function used to translate strings (often ugettext) is often renamed locally to _ () so that it takes up as much screen space as possible:

 from django.utils.translation import ugettext as _

 print(_("This is a translatable string."))

      

+1


source


'_'

is a legitimate symbol for python, like most other programming languages. I think MATLAB is an exception where you cannot use this for any MATLAB file names. I know because I have tried this in the past and it has failed. Don't know if this has been changed since R2014b. The best examples are the python __init__

, __self__

, __str__

, __repr__

etc.

Instead of asking questions and having confusion in your mind, just type it in and see what happens. You won't break anything: D. Open PLEON IDLE and press CTRL +. you will see many native Python variables and functions named _

or even __

. I really liked the @iCodez variable assignment example here :)

0


source







All Articles