8000 Use mypy-friendly conditional import for zoneinfo by KapJI · Pull Request #50444 · home-assistant/core · GitHub
[go: up one dir, main page]

Skip to content

Use mypy-friendly conditional import for zoneinfo #50444

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
10000 Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions homeassistant/util/dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@
from contextlib import suppress
import datetime as dt
import re
from typing import Any

try:
import zoneinfo
except ImportError:
from backports import zoneinfo
import sys
from typing import Any, cast

import ciso8601

from homeassistant.const import MATCH_ALL

if sys.version_info[:2] >= (3, 9):
import zoneinfo # pylint: disable=import-error
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cdce8p if you want to improve pylint a little bit more.

Mypy understands blocks inside sys.version_info but pylint doesn't. But on the other side pylint doesn't complain about

try:
  import x
except ImportError
  import y

while mypy has this issue.

It'd be nice to support sys.version_info in pylint as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could use the ignored-modules option, documentation or wait for pylint-dev/pylint#4468 😃

else:
from backports import zoneinfo # pylint: disable=import-error

DATE_STR_FORMAT = "%Y-%m-%d"
UTC = dt.timezone.utc
DEFAULT_TIME_ZONE: dt.tzinfo = dt.timezone.utc
Expand Down Expand Up @@ -48,7 +49,8 @@ def get_time_zone(time_zone_str: str) -> dt.tzinfo | None:
Async friendly.
"""
try:
return zoneinfo.ZoneInfo(time_zone_str) # type: ignore
# Cast can be removed when mypy is switched to Python 3.9.
return cast(dt.tzinfo, zoneinfo.ZoneInfo(time_zone_str))
except zoneinfo.ZoneInfoNotFoundError:
return None

Expand Down
0