Consider the following
from datetime import datetime
def tle_request(date_time: list[int]) -> datetime:
# Attempting to create a datetime object using unpacking
general_date: datetime = datetime(*date_time[:3]) # This causes a mypy error
return general_date
# Example usage
my_time = tle_request([2023, 9, 27])
print(f"Hello {my_time}")
Although it works:
❯ python main.py
Hello 2023-09-27 00:00:00
mypy is prompting the following error:
❯ mypy main.py
main.py:5: error: Argument 1 to "datetime" has incompatible type "*list[int]"; expected "tzinfo | None" [arg-type]
Found 1 error in 1 file (checked 1 source file)
That is very weird because if I change datetime(*date_time[:3]) with datetime(date_time[0], date_time[1], date_time[2]). I works:
❯ mypy main.py
Success: no issues found in 1 source file
Why? Unpacking is really necessary and I see no reason for mypy to complain about it.
*datetime[:3]as the parameter passed todatetime? You are currently passingdate_time[0], date_time[1], date_time[2]but then later mention replacing*datetime[:3]withdate_time[0], date_time[1], date_time[2]mypy. Your signature allowstle_request([1]). It's fine to slice a list to a longer length ([1][:3]is[1]), sodatetimecall will fail. Slicing restricts the upper limit ("list no longer than three items"), but does not guarantee the lower limit.