Testing if an object is None and assigning it
suggest changeYou’ll often want to assign something to an object if it is None, indicating it has not been assigned. We’ll use aDate.
The simplest way to do this is to use the is None test.
import datetime
if aDate is None:
aDate = datetime.date.today()
(Note that it is more Pythonic to say is None instead of == None.)
not aDate is not the same test. It is also true for 0, '', and every other falsy value:
if not aDate:
aDate = datetime.date.today()
This short-circuit form has the same limitation. datetime.date.today() runs only when aDate is falsy, not only when it is None:
aDate = aDate or datetime.date.today()
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents