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)
243.0
>>> result = _
>>> result
243.0
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.
The following GLOBAL variables always exist (so don’t overwrite them!):
[_] (a single underscore) : stores previous output, like Python’s default interpreter.
[...]
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).
In loops, 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.