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 >>>
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With