19

私が知っている他のいくつかの言語では、null から文字列への変換の直感的な結果は空の文字列になるはずです。Python が「None」を一種の特別な文字列にするように設計されているのはなぜですか? これにより、関数からの戻り値をチェックするときに余分な作業が発生する可能性があります

result = foo() # foo will return None if failure 
if result is not None and len(str(result)) > 0:
    # ... deal with result 
    pass 

str(None) が空の文字列を返す場合、コードは短くなる可能性があります。

if len(str(result)) > 0:
    # ... deal with result 
    pass 

ログファイルをより理解しやすくするために、Pythonは冗長になろうとしているように見えますか?

4

2 に答える 2

15

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?

于 2013-07-17T04:35:38.800 に答える