Reputation: 13642
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.
Upvotes: 2
Views: 578
Reputation: 1121196
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.
Upvotes: 4