为什么,b=1,2,3在IPython中被解析为(',b','=',1,2,3')?

2024-06-25 23:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我注意到IPython在语法上有一些非常奇怪的解析行为,这不是合法的Python。你知道吗

In [1]: ,,b = 1,2,3
Out[1]: (',b', '=', '1,2,3')

分号也有类似的情况,但它不会分裂成元组。你知道吗

In [4]: ;;foo = 1;2;3
Out[4]: ';foo = 1;2;3'

虽然看起来;意味着行的其余部分被视为文本字符串,但情况并非总是这样:

In [5]: ,foo
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-f2137ad20ab5> in <module>()
----> 1 foo("")

NameError: name 'foo' is not defined

In [6]: ;foo
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-f2137ad20ab5> in <module>()
----> 1 foo("")

NameError: name 'foo' is not defined

为什么伊普顿要这么做?这是文件化的还是可配置的?你知道吗


Tags: inmostinputfooipython情况callout
1条回答
网友
1楼 · 发布于 2024-06-25 23:02:18

这是一种方便的强制引用方法,请参见文档:https://ipython.readthedocs.io/en/stable/interactive/reference.html#automatic-parentheses-and-quotes

从文档中:

You can force automatic quoting of a function’s arguments by using , or ; as the first character of a line. For example:

In [1]: ,my_function /home/me  # becomes my_function("/home/me") 

If you use ‘;’ the whole argument is quoted as a single string, while ‘,’ splits on whitespace:

In [2]: ,my_function a b c    # becomes my_function("a","b","c")
In [3]: ;my_function a b c    # becomes my_function("a b c")

Note that the ‘,’ or ‘;’ MUST be the first character on the line! This won’t work:

In [4]: x = ,my_function /home/me # syntax error

例如,;只输出一个空字符串:

In [260]:

;
Out[260]:
''

就像逗号一样,

In [261]:

,
Out[261]:
''

我看不到任何地方允许你覆盖这个,我可能是错的,但它看起来像是硬编码的东西。你知道吗

编辑

好的,我发现了一篇mail关于这个的帖子,你可以通过添加(或者如果它不存在的话创建)以下内容来关闭它.ipython/profile_default/static/custom/custom.js,这是未测试的:

if (IPython.CodeCell) {
    IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
}

关于为什么,,b = 1,2,3被区别对待的最后一点,看起来空格引入了某种中断,然后将其转换为元组:

In [9]:

,,b =

Out[9]:
(',b', '=')

与无空格比较:

In [10]:

,,b=
Out[10]:
',b='

相关问题 更多 >