oldstr(None) 引发异常:无法将“NoneType”对象转换为字节

时间:2020-12-20 13:44:00

标签: python python-3.x python-2.7

将 PY2 移植到 PY3 时,我使用的是 future library。我尝试 str(None) 但它失败了,但 py2 和 py3 都支持 str(None)。 这是一个python错误还是所需的行为?

试试这个:

In[6]: from past.builtins import str as oldstr
In[7]: oldstr(None)
Traceback (most recent call last):
  File "../venv/py3_env/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-7-42dcefbf9e2f>", line 1, in <module>
    oldstr(None)
TypeError: cannot convert 'NoneType' object to bytes
In[8]: str(None)
Out[8]: 'None'

1 个答案:

答案 0 :(得分:0)

众所周知,str是python的内置函数:

内置的 str 函数不会抛出错误,但

当你使用同一个函数 str 和别名时。

我可以用另一种方式来解释:


import past

### past.builtins.str() is from module

### str() is the in-built function of python when you type "str()" in your code it always uses the str() in-built 

### You can see that the str in-built function is colored in syntax highlighting.


past.builtins.str() != str() # in-built str()

最后,代码运行正确。

在 past.builtins.str() 中有一个错误,而不是在内置的 str() 中

要将其用作 str 将代码更改为:

from past.builtins import str as str 

from past.builtins import str # same thing

oldstr(None) # 预期错误:没有这样的函数。

str(None) # 预期错误:

Traceback (most recent call last):
  File "../venv/py3_env/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-7-42dcefbf9e2f>", line 1, in <module>
    str(None)
TypeError: cannot convert 'NoneType' object to bytes