python - 在方法内的 %time 语句中定义的变量在该语句之后不可访问

标签 python python-2.7 ipython

这似乎工作正常 -

%time a = "abc"
print(a)

CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 19.1 µs
abc

这不是 -

def func():
    %time b = "abc"
    print(b)

func()

CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 31 µs
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-57f7d48952b8> in <module>()
      3     print(b)
      4 
----> 5 func()

<ipython-input-8-57f7d48952b8> in func()
      1 def func():
      2     get_ipython().magic(u'time b = "abc"')
----> 3     print(b)
      4 
      5 func()

NameError: global name 'b' is not defined

这是一个指向 notebook 的链接

我使用的是 python 2.7,还没有尝试过 python3。

这是预期的行为吗?

最佳答案

我几乎可以肯定这是一个 IPython 错误。 Reported here .

In [31]: def func():
    ...:     a = 2
    ...:     %time b = 1
    ...:     print(locals())
    ...:     print a
    ...:     print b

In [32]: func()
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 6.2 µs
{'a': 2, 'b': 1}
2
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-32-08a2da4138f6> in <module>()
----> 1 func()

<ipython-input-31-13da62c18a7e> in func()
      4     print(locals())
      5     print a
----> 6     print b
      7
      8

NameError: global name 'b' is not defined

关于python - 在方法内的 %time 语句中定义的变量在该语句之后不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39067203/

相关文章:

linux - 使用 ucs4 问题构建 numpy

python - 将 unicode 字符串打印到控制台正常,但在重定向到文件时失败。怎么修?

python - 如何在 Python 中构建朴素贝叶斯模型时使用时间戳数据

python - 如何在 PyCharm 中设置 ipython 配置文件

Python - 在服务器端解析多部分/表单数据请求

python - 删除keras预训练模型层

python - cvtColor “code”用于16位灰度图像

python - 将mysql中的2个数据字段与python进行比较

ipython - 如何在 IPython 中重置 MathJax 设置?

python - IPython 终端使用哪种字符编码?