Python `None` passed into type-conversion functions

我们两清 提交于 2020-01-04 15:15:28

问题


What is the rationale for the design decision for None type being passed into type-conversion functions?

  • bool(None) returns False - which makes perfect sense

  • str(None) returns 'None' which is not okay - Returning an empty string would be a better choice as below

    >>> bool(None)
    False
    >>> bool(str(None))     #Returning empty string will make it consistent by returning False
    True
    >>> bool('')
    False
    
  • And list(None), dict(None), tuple(None), int(None), float(None) return Type errors - From which if they return [], {}, (), 0 and 0.0 it would have been a obvious and will be useful in many real life scenarios to avoid manual handling.

It's appreciated If someone could explain what might have motivated Guido to go the other way around.

PS : This arose from this question Python: most idiomatic way to convert None to empty string?. Most of the answers are of if-else approaches where as in real life converting/overriding None by empty string, list, dict or 0 would be common.


回答1:


None is still an object. It is not an empty value, it is merely a sentinel to use anywhere you have to produce or use an object but you really wanted to leave it empty.

Function calls don't require an argument, calling something with no arguments is perfectly valid. As such there is no point in passing in None, as that would be one argument, not zero.

To create 'empty' objects using the type functions then, just leave the argument list empty:

>>> list()
[]
>>> tuple()
()
>>> str()
''

bool() gives you the boolean type of the argument you passed in. You can call it without an argument:

>>> bool()
False

but if you pass in None, it'll determine the truth value of that object. For None that value is False. str(None) produces the string 'None', which is not empty so it is True when passed to bool(). See the Truth Value Testing section.



来源:https://stackoverflow.com/questions/31245175/python-none-passed-into-type-conversion-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!