thebat
thebat

Reputation: 2089

Is the single underscore "_" a built-in variable in 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
>>> 

Upvotes: 38

Views: 6530

Answers (3)

Mark Rushakoff
Mark Rushakoff

Reputation: 258358

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).

Upvotes: 57

u0b34a0f6ae
u0b34a0f6ae

Reputation: 49813

Why you can't see it? It is in __builtins__

>>> __builtins__._ is _
True

So it's neither global nor local. 1

And where does this assignment happen? sys.displayhook:

>>> import sys
>>> help(sys.displayhook)
Help on built-in function displayhook in module sys:

displayhook(...)
    displayhook(object) -> None

    Print an object to sys.stdout and also save it in __builtin__.

1 2012 Edit : I'd call it "superglobal" since __builtin__'s members are available everywhere, in any module.

Upvotes: 19

Natim
Natim

Reputation: 18112

Usually, we are using _ in Python to bind a ugettext function.

Upvotes: 2

Related Questions