在Python / IPython解释器中为单个下划线_赋值 [英] Assigning a value to single underscore _ in Python/IPython interpreter

查看:234
本文介绍了在Python / IPython解释器中为单个下划线_赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 2.7中用 ipython 创建了这个函数:

  def _(v):
return v

稍后如果我调用 _(somevalue),我得到 _ = somevalue

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

该功能已经消失!如果我打电话给 _(4),我会得到:

  TypeError:' int'object is callable` 

为什么?这个函数有什么问题?

解决方案

Python解释器将最后一个表达式值赋给 _



此行为仅限于










$ b $ >>>导入数学
>>> math.pow(3.0,5)
243.0
>>> result = _
>>>结果
243.0

标准 Python解释器有一定长度不要践踏用户定义的值;如果你自己把 else 赋值给 _ ,那么解释器不会覆盖它(从技术上讲, _ variable是一个 __ builtin __ 属性,您自己的任务是常规全局变量)。你虽然没有使用标准的Python解释器,你正在使用IPython,而且这个解释器并不那么小心。



IPython 明确地记录了这种行为

lockquote

以下GLOBAL变量总是存在的(所以不要覆盖它们):


  • [_] (单个下划线):存储以前的输出,如Python的默认解释器。



[...]


在Python解释器之外, _ 通常用作可翻译文本函数的名称(请参阅 gettext module a>;外部工具查找该函数来提取可翻译的字符串)。

在循环中,使用 _ 作为分配目标告诉读者你的代码你将忽略该值;例如 [random.random()for _ in range(5)] 生成一个包含5个随机浮点值的列表。


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.

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.

[...]

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.

这篇关于在Python / IPython解释器中为单个下划线_赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆