Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

function - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...