当运算符与=符号一起使用时,运算符会做什么?

时间:2017-08-06 16:19:31

标签: python python-3.x ipython

我完全随机地发现了这只好奇,因为这看起来并不像一个列表。

2 个答案:

答案 0 :(得分:2)

这是在IPython中实现自动引用功能的a weird side-effect。特别是,在IPython终端输入的每一行都与this regex pattern进行了模式匹配:

import re
line_split = re.compile("""
             ^(\s*)               # any leading space
             ([,;/%]|!!?|\?\??)?  # escape character or characters
             \s*(%{0,2}[\w\.\*]*)     # function/method, possibly with leading %
                                  # to correctly treat things like '?%magic'
             (.*?$|$)             # rest of line
             """, re.VERBOSE)

如果输入', = what iss this',则会产生the following assignments

pre, esc, ifun, the_rest = line_split.match(', = what iss this').groups()
print(repr(pre))
# ''

print(repr(esc))
# ','

print(repr(ifun))
# ''

print(repr(the_rest))
# '= what iss this'

由于esc是逗号,the AutoHandler prefilter到达此if-else声明:

    if esc == ESC_QUOTE:
        # Auto-quote splitting on whitespace
        newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )

修改命令成为

In [19]: ifun=''

In [20]: the_rest='= what iss this'

In [21]: newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )

In [22]: newcmd
Out[22]: '("=", "what", "iss", "this")'

总而言之,

  • 初始逗号触发IPython的自动引用功能。
  • 由于未找到有效的函数名称,ifun为空字符串
  • 自动引用引用命令字符串和表单的其余部分

    '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
    

    作为新命令。这个"命令"然后进行评估。

因此,返回的结果是元组("=", "what", "iss", "this")

答案 1 :(得分:1)

只需在IPython中使用?即可查看 IPython功能的介绍和概述。

  
      
  1. 自动竞标

         

    您可以使用','强制自动引用函数的参数    一行的第一个字符。例如::

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

    如果使用';'相反,整个论点被引用为单一    string(而','在空格上分割)::

      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")
    
         

    请注意,','必须是该行的第一个字符!这个    不会起作用::

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

编辑:=解释感到抱歉。正如@randomir所说,= op讨论的是here

相关问题