Assigning a value to single underscore _ in Python/IPython interpreter

I created this function in Python 2.7 with ipython:

    def _(v):
        return v

later if I call _(somevalue), I get _ = somevalue.

    in[3]: _(3)
    out[3]: 3
    in[4]: print _
    out[4]: 3

The function has disappeared! If I call _(4) I get:

    TypeError: 'int' object is not callable`

Why? What's wrong with this function?

The Python interpreter assigns the last expression value to _.

This behaviour is limited to the REPL interpreter only, and is intended to assist in interactive coding sessions:

    >>> import math
    >>> math.pow(3.0, 5)
    >>> result = _
    >>> result

The standard Python interpreter goes to some length to not trample on user-defined values though; if you yourself assign something else to _ then the interpreter will not overwrite that (technically speaking, the _ variable is a __builtin__ attribute, your own assignments are 'regular' globals). You are not using the standard Python interpreter though; you are using IPython, and that interpreter is not that careful.

IPython documents this behaviour explicitly:

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

  • [_] (a single underscore) : stores previous output, like Python’s default interpreter.


In the standard Python REPL environment, if you assigned something to _ you can still access the last expression result via __builtins__._ or by deleting the _ global that shadows it again (del _).

Outside of the Python interpreter, _ is by convention used as the name of the translatable text function (see the gettext module; external tools look for that function to extract translatable strings).

And, also by convention, using _ as an assignment target tells readers of your code that you are going to ignore that value; e.g. [random.random() for _ in range(5)] to generate a list of 5 random float values, or foo, bar, _ = three_values to signal a 3rd value from a tuple assignment will not be used. When _ is already used for a gettext function, __ can be used for the same purposes.