result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
甚至..。
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
There's no reason to automatically use 0 here — solutions that depend on the "false"-ness of None assume you will want this. The DEFAULT_VALUE (if it even exists) completely depends on your code's purpose.
import sys, email, email.Utils
afile = open(sys.argv[1], 'r')
m = email.message_from_file(afile)
subject = m["subject"]
# Soviut's Concise test for unset variable.
if subject is None:
subject = "[NO SUBJECT]"
# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)
try:
if len(subject) == 0:
subject = "[NO SUBJECT]"
except TypeError:
subject = "[NO SUBJECT]"
print subject
afile.close()
对于这种类型的错误,我已经成功地使用了 int (x 或0) ,只要在逻辑中 Nothing 应该等于0。
Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string.
抱歉,金德尔已经回答过了。