Skip to content

datetime.datetime is not Liskov-substitutable for datetime.date, but it's typed as if it were #3805

@glyph

Description

@glyph

Consider this code:

import datetime

def compare_dates(x: datetime.date, y: datetime.date) -> bool:
    return x > y

compare_dates(datetime.datetime.now(), datetime.date.today())

Under mypy, it typechecks. Mypy's job is to prevent runtime TypeErrors, right? At runtime:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
    compare_dates(datetime.datetime.now(), datetime.date.today())
  File "<input>", line 2, in compare_dates
    return x > y
TypeError: can't compare datetime.datetime to datetime.date

I think #2487 was wrong, and it actually makes more sense to type datetime.date and datetime.datetime separately.

Perhaps this is a mypy bug though? Maybe just because something's a subclass, doesn't mean it should be a subtype? Or a bug in datetime because it shouldn't do this?

I'm not sure. But practically speaking this makes any code working with date objects in mypy somewhat misleading and fraught.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions