I’m currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn’t an instance of datetime. Surely there’s a better way?
from datetime import date, datetime
def some_func(arg):
assert isinstance(arg, date) and not isinstance(arg, datetime),\
'arg must be a datetime.date object'
# ...
I don’t understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that’s really what you insist on doing, then:
Don’t use
assertexcept for sanity check during development (it gets turned to a no-op when you run withpython -o), and don’t raise the wrong kind of exception (such as, anAssertionErrorwhen aTypeErroris clearly what you mean here).Using
isinstanceand then excluding one specific subclass is not a sound way to get a rigidly specified exact type with subclasses excluded: after all, the user might perfectly well subclassdatetime.dateand add whatever it is you’re so keep to avoid by rejecting instances ofdatetime.datetimespecifically!-)