考虑以下情况
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}")
尽管它有效:
❯ python main.py
Hello 2023-09-27 00:00:00
mypy
提示以下错误:
❯ 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)
这很奇怪,因为如果我datetime(*date_time[:3])
用datetime(date_time[0], date_time[1], date_time[2])
. 进行更改,则可以:
❯ mypy main.py
Success: no issues found in 1 source file
为什么?拆包确实是必要的,我看不出有什么理由mypy
抱怨。