Why python designed as str(None) return 'None' instead of an empty string?

python

Solution

Checking if a string has characters in it by checking `len(str(result))` is definitely not pythonic (see http://www.python.org/dev/peps/pep-0008/).

result = foo() # foo will return None if failure 
if result:
    # deal with result.
    pass

`None` and `''` coerce to the boolean `False`.

If you are really asking why `str(None)` does return `'None'`, then I believe it is because it is necessary for three-valued logic. `True`, `False` and `None` can be used together to determine if a logical expression is `True`, `False` or cannot be decided. The identity function is the easiest for representation.

True  -> 'True'
False -> 'False'
None  -> 'None'

The following would be really weird if `str(None)` was `''`:

>>> or_statement = lambda a, b: "%s or %s = %s" % (a, b, a or b)
>>> or_statement(True, False)
'True or False = True'
>>> or_statement(True, None)
'True or None = True'
>>> or_statement(None, None)
'None or None = None'

Now, if you really want for an authoritative answer, ask Guido.

If you really want to have `str(None)` give you `''` please read this other question: Python: most idiomatic way to convert None to empty string?

Problem

In some other languages I knows, the intuitive result of a null to string conversion should be an empty string. Why Python is designed to make 'None' be sort of special string? And this can lead to extra work when checking a return value from a function ``` result = foo() # foo will return None if failure if result is not None and len(str(result)) > 0: # ... deal with result pass ``` if str(None) returns empty string, the code could be shorter: ``` if len(str(result)) > 0: # ... deal with result pass ``` Looks like Python is trying to be verbose, to make log files be more understandable?

Original source

Related problems