Make datetime.IsoCalendarDate publicly available

Hi,

I use datetime.date.isocalendar() a lot and I was wondering why it’s return type (IsoCalendarDate) wasn’t part of datetime public API?

I missed it a few times when typing functions using ISO week-numbering dates as input / output, for example

def format_iso_date(iso_date: datetime.IsoCalendarDate) -> str:  # invalid type
    return f"{iso_date.year:04}-W{iso_date.week:02}-{iso_date.weekday}"

which seems a pretty fair use case to me. I could of course pass datetime objects and call isocalendar() inside the function, but I’d rater not to avoid multipe conversions.

I suppose this class is directly implemented in C if the module is installed, without Python interface so it we can’t make it instanciable, but maybe it could be available only for typing? While not really useful before 3.9 (when isocalendar() returned a tuple and not a namedtuple), I think could be now.

Thanks!

Note the following workaround seems to work, at least with my setup:

from typing import TYPE_CHECKING 

if TYPE_CHECKING:
    from datetime import _IsoCalendarDate 
 
def format_iso_date(iso_date: "_IsoCalendarDate") -> str: ...

But it’s not really satisfying and looks more like an implementation detail.

I think because it is an implementation detail…?

The docs simply say that the return value is a named tuple. And the stdlib deliberately doesn’t include type hints directly (they are provided by typeshed, not by the stdlib) so there’s no need in the stdlib to expose the internal name of the namedtuple type returned.

Maybe it would be useful to document and expose that type directly, but that opens up the whole question of how much the stdlib should expose such type-specific information? And that’s a question we’ve so far avoided.

1 Like