Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the single underscore "_" a built-in variable in Python?

Tags:

python

I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().

>>> 'abc' 'abc' >>> len(_) 3 >>>  
like image 389
thebat Avatar asked Oct 08 '09 16:10

thebat


People also ask

What is single underscore in Python?

A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally. This is more of a syntax hint to the programmer and is not enforced by the Python interpreter which means that these objects can still be accessed in one way on another from another script.

What does __ means in Python?

Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want. You can use it as a normal variable.

What is underscore _ init _ underscore in Python?

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. This isn't enforced by Python. Python does not have strong distinctions between “private” and “public” variables like Java does.

What is _ in Python class?

The python interpreter stores the last expression value to the special variable called '_'. This feature has been used in standard CPython interpreter first and you could use it in other Python interpreters too.


1 Answers

In the standard Python REPL, _ represents the last returned value -- at the point where you called len(_), _ was the value 'abc'.

For example:

>>> 10 10 >>> _ 10 >>> _ + 5 15 >>> _ + 5 20 

This is handled by sys.displayhook, and the _ variable goes in the builtins namespace with things like int and sum, which is why you couldn't find it in globals().

Note that there is no such functionality within Python scripts. In a script, _ has no special meaning and will not be automatically set to the value produced by the previous statement.

Also, beware of reassigning _ in the REPL if you want to use it like above!

>>> _ = "underscore" >>> 10 10 >>> _ + 5  Traceback (most recent call last):   File "<pyshell#6>", line 1, in <module>     _ + 5 TypeError: cannot concatenate 'str' and 'int' objects 

This creates a global variable that hides the _ variable in the built-ins. To undo the assignment (and remove the _ from globals), you'll have to:

>>> del _ 

then the functionality will be back to normal (the builtins._ will be visible again).

like image 94
Mark Rushakoff Avatar answered Sep 19 '22 19:09

Mark Rushakoff