tags:

views:

253

answers:

3

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
>>>
+10  A: 

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

Note that there is no such functionality within Python scripts. In a script, _ is just your run-of-the-mill identifier.

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

To undo the assignment (and remove the _ from globals), you'll have to:

>>> del _

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

Mark Rushakoff
FYI: REPL is short for Read-Eval-Print Loop. As always, wikipedia has more info if you want it. http://en.wikipedia.org/wiki/Read-eval-print_loop
David Locke
+7  A: 

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

>>> __builtins__._ is _
True

So it's neither global nor local.

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__.
kaizer.se
A: 

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

Natim
this is also true, but only for Python Applications. `gettext.install` will bind to `__builtins__._`, so that it is available without importing in all of the application; thus the same kind of "magic" name.
kaizer.se