为什么整数上升ndigits = None而不是浮点数?

时间:2016-09-01 14:23:54

标签: python rounding python-3.5

round()明确设置为ndigits时,为什么None对于int和float的行为不同?

Python 3.5.1中的控制台测试:

>>> round(1, None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object cannot be interpreted as an integer
>>> round(1.0, None)
1

更新

我将此报告为已修复并关闭的错误(Issue #27936)。 @PadraicCunningham和@CraigBurgler是正确的。

该修复程序包含在以下最终版本中:

1 个答案:

答案 0 :(得分:3)

来自float_roundfloatobjects.c的{​​{1}}的源代码:

3.5

float_round(PyObject *v, PyObject *args) ... if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) return NULL; ... if (o_ndigits == NULL || o_ndigits == Py_None) { /* single-argument round or with None ndigits: * round to nearest integer */ ... 位显式捕获|| o_ndigits == Py_None参数并将其丢弃,将ndigits=None的调用视为单参数调用。

round中,此代码如下所示:

3.4

没有float_round(PyObject *v, PyObject *args) ... if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) return NULL; ... if (o_ndigits == NULL) { /* single-argument round: round to nearest integer */ ... 测试,因此|| o_ndigits == Py_None参数落空并被视为ndgits=None,从而导致int TypeError round(1.0, None) {1}}。

3.4o_ndigits == Py_None long_round的{​​{1}}中longobject.c无法检查3.4,因此3.5 TypeErrorround(1, None)3.4

中都有1}}
3.5
相关问题