有时,地图是一个序列,有时不是?

时间:2014-03-21 12:35:30

标签: python python-3.x map

在python3中,当我尝试执行以下行时:

$ python3
Python 3.3.5 (default, Mar 18 2014, 02:00:02) 
[GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.
>>> def fail(arg):
...   raise Exception
... 
>>> def fail_type(arg):
...   raise TypeError
... 
>>> identity = lambda x: x
>>> m = [0,1]
>>> print("{:8.2f}{:8.2f}".format(*map(identity, m)))
    0.00    1.00
>>> print("{:8.2f}{:8.2f}".format(*map(fail, m)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fail
Exception
>>> print("{:8.2f}{:8.2f}".format(*map(fail_type, m)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: format() argument after * must be a sequence, not map
>>> list(map(identity, m))
[0, 1]
>>> list(map(fail, m))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fail
Exception
>>> list(map(fail_type, m))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fail_type
TypeError
>>> 

为什么python会在我看来极为误导TypeError: format() argument after * must be a sequence, not map这个内置函数?如果发现其他raise的明确Exception被捕获,则会更加令人困惑。在*错误处理中是否存在假设TypeError必须归因于参数列表不是序列?

1 个答案:

答案 0 :(得分:5)

TypeError异常匹配发生在ext_do_call(Python / ceval.c,第4507行)中,调用它来处理操作码CALL_FUNCTION_VARCALL_FUNCTION_KW和{ {1}}。它假设PySequence_Tuple提出CALL_FUNCTION_VAR_KW,因为参数不可迭代,正如PyObject_GetIter提出的那样。

在补丁评论&#34;中有一个已打开的Python错误。阶段3年:Function calls taking a generator as star argument can mask TypeErrors in the generator