nehem
nehem

Reputation: 13642

Python `None` passed into type-conversion functions

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

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

Answers (1)

Martijn Pieters
Martijn Pieters

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

Related Questions