Skip to content

Commit

Permalink
py3.10 upgrade: pyupgrade (additional isort, black and clean up)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldotlopez committed Jun 30, 2023
1 parent eab4dae commit 3509f3e
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 60 deletions.
10 changes: 3 additions & 7 deletions custom_components/ideenergy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand All @@ -23,17 +21,15 @@
import math
from datetime import timedelta

import ideenergy
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_PASSWORD,
CONF_USERNAME,
)
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo

import ideenergy

from .barrier import TimeDeltaBarrier, TimeWindowBarrier # NoopBarrier,
from .const import (
API_USER_SESSION_TIMEOUT,
Expand Down
12 changes: 5 additions & 7 deletions custom_components/ideenergy/barrier.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand All @@ -24,9 +22,9 @@
import logging
from abc import abstractmethod
from datetime import timedelta
from typing import Any, Optional, Tuple, Union
from typing import Any

from homeassistant.util import dt as dt_util
from homeassistant.core import dt_util

_LOGGER = logging.getLogger(__name__)

Expand All @@ -46,7 +44,7 @@


def check_tzinfo(
param: Union[str, int], default_tzinfo=datetime.timezone.utc, optional=False
param: str | int, default_tzinfo=datetime.timezone.utc, optional=False
):
def decorator(fn):
@functools.wraps(fn)
Expand Down Expand Up @@ -118,7 +116,7 @@ class TimeDeltaBarrier(Barrier):
def __init__(
self,
delta: datetime.timedelta,
last_success: Optional[datetime.datetime] = None,
last_success: datetime.datetime | None = None,
):
self._delta = delta
self._last_success = last_success or dt_util.utc_from_timestamp(0)
Expand Down Expand Up @@ -178,7 +176,7 @@ def max_retries(self):
class TimeWindowBarrier(Barrier):
def __init__(
self,
allowed_window_minutes: Tuple[int, int],
allowed_window_minutes: tuple[int, int],
max_retries: int,
max_age: timedelta,
):
Expand Down
12 changes: 6 additions & 6 deletions custom_components/ideenergy/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Luis López <luis@cuarentaydos.com>
#
Expand All @@ -19,18 +18,19 @@


import os
from typing import Any, Optional
from typing import Any

import ideenergy
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback # noqa: F401
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_create_clientsession

import ideenergy

from . import _LOGGER
from .const import CONF_CONTRACT, DOMAIN, CONFIG_ENTRY_VERSION
from .const import CONF_CONTRACT, CONFIG_ENTRY_VERSION, DOMAIN

AUTH_SCHEMA = vol.Schema(
{
Expand All @@ -54,7 +54,7 @@ def __init__(self, *args, **kwargs):
# return OptionsFlowHandler(config_entry)

async def async_step_user(
self, user_input: Optional[dict[str, Any]] = None
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle a flow initialized by the user."""
errors = {}
Expand Down Expand Up @@ -95,7 +95,7 @@ async def async_step_user(
)

async def async_step_contract(
self, user_input: Optional[dict[str, Any]] = None
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
contracts = await self.api.get_contracts()
contracts = {f"{x['cups']} ({x['direccion']})": x for x in contracts}
Expand Down
2 changes: 0 additions & 2 deletions custom_components/ideenergy/const.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand Down
23 changes: 10 additions & 13 deletions custom_components/ideenergy/datacoordinator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand All @@ -21,13 +19,12 @@
import enum
import logging
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional, Union
from typing import Any

from homeassistant.core import dt_util
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

import ideenergy
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
) # ConfigEntryAuthFailed,; UpdateFailed
from homeassistant.util import dt as dt_util

from .barrier import Barrier, BarrierDeniedError
from .const import (
Expand All @@ -53,7 +50,7 @@ class DataSetType(enum.IntFlag):

_LOGGER = logging.getLogger(__name__)

_DEFAULT_COORDINATOR_DATA: Dict[str, Any] = {
_DEFAULT_COORDINATOR_DATA: dict[str, Any] = {
DATA_ATTR_MEASURE_ACCUMULATED: None,
DATA_ATTR_MEASURE_INSTANT: None,
DATA_ATTR_HISTORICAL_CONSUMPTION: {
Expand All @@ -75,7 +72,7 @@ def __init__(
self,
hass,
api,
barriers: Dict[DataSetType, Barrier],
barriers: dict[DataSetType, Barrier],
update_interval: timedelta = timedelta(seconds=30),
):
name = (
Expand All @@ -96,7 +93,7 @@ def unregister_sensor(self, sensor: IDeEntity) -> None:
_LOGGER.debug(f"Unregistered sensor '{sensor.__class__.__name__}'")
self.sensors.remove(sensor)

def update_internal_data(self, data: Dict[str, Any]):
def update_internal_data(self, data: dict[str, Any]):
if self.data is None: # type: ignore[has-type]
self.data = _DEFAULT_COORDINATOR_DATA

Expand Down Expand Up @@ -133,8 +130,8 @@ async def _async_update_data(self):
return data

async def _async_update_data_raw(
self, datasets: DataSetType = DataSetType.ALL, now: Optional[datetime] = None
) -> Dict[str, Any]:
self, datasets: DataSetType = DataSetType.ALL, now: datetime | None = None
) -> dict[str, Any]:
now = now or dt_util.utcnow()
if now.tzinfo != timezone.utc:
raise ValueError("now is missing tzinfo field")
Expand Down Expand Up @@ -217,7 +214,7 @@ async def _async_update_data_raw(

return data

async def get_direct_reading_data(self) -> Dict[str, Union[int, float]]:
async def get_direct_reading_data(self) -> dict[str, int | float]:
data = await self.api.get_measure()

return {
Expand Down
5 changes: 1 addition & 4 deletions custom_components/ideenergy/entity.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand All @@ -23,7 +21,6 @@
# from homeassistant.core import callback

import logging
from typing import Type

from homeassistant.components import recorder
from homeassistant.helpers.entity import DeviceInfo
Expand All @@ -34,7 +31,7 @@
hass_recorder_session,
)

SensorType = Type["IDeEntity"]
SensorType = type["IDeEntity"]


_LOGGER = logging.getLogger(__name__)
Expand Down
2 changes: 0 additions & 2 deletions custom_components/ideenergy/fixes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand Down
18 changes: 8 additions & 10 deletions custom_components/ideenergy/sensor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand Down Expand Up @@ -32,7 +30,7 @@

# import statistics
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, List, Optional
from typing import Any, Callable

from homeassistant.components import recorder
from homeassistant.components.recorder import statistics
Expand All @@ -49,7 +47,7 @@
UnitOfEnergy,
UnitOfPower,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import HomeAssistant, callback, dt_util
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import DiscoveryInfoType
Expand Down Expand Up @@ -111,8 +109,8 @@ async def async_added_to_hass(self):
await fixes.async_fix_statistics(self.hass, self.get_statatistic_metadata())

async def async_calculate_statistic_data(
self, hist_states: List[HistoricalState], *, latest: Optional[dict]
) -> List[StatisticData]:
self, hist_states: list[HistoricalState], *, latest: dict | None
) -> list[StatisticData]:

#
# Filter out invalid states
Expand Down Expand Up @@ -157,7 +155,7 @@ def get_last_statistics():
1,
self.statatistic_id,
convert_units=True,
types=set(["last_reset", "max", "mean", "min", "state", "sum"]),
types={"last_reset", "max", "mean", "min", "state", "sum"},
)
if ret is None:
return None
Expand Down Expand Up @@ -379,7 +377,7 @@ async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_devices: AddEntitiesCallback,
discovery_info: Optional[DiscoveryInfoType] = None, # noqa DiscoveryInfoType | None
discovery_info: DiscoveryInfoType | None = None, # noqa DiscoveryInfoType | None
):
coordinator, device_info = hass.data[DOMAIN][config_entry.entry_id]

Expand All @@ -404,8 +402,8 @@ async def async_setup_entry(


def historical_states_from_historical_api_data(
data: Optional[List[Dict]] = None,
) -> List[HistoricalState]:
data: list[dict] | None = None,
) -> list[HistoricalState]:
def _convert_item(item):
# FIXME: What about canary islands?
dt = item["end"].replace(tzinfo=MAINLAND_SPAIN_ZONEINFO)
Expand Down
12 changes: 3 additions & 9 deletions custom_components/ideenergy/updates.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (C) 2021-2022 Luis López <luis@cuarentaydos.com>
#
# This program is free software; you can redistribute it and/or
Expand All @@ -19,7 +17,6 @@


import logging
from typing import Type

from custom_components.ideenergy.const import DOMAIN
from homeassistant.config_entries import ConfigEntry
Expand All @@ -28,16 +25,13 @@
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.util import slugify

from .entity import (
_build_entity_entity_id as _build_entity_entity_id_v3,
_build_entity_unique_id as _build_entity_unique_id_v3,
IDeEntity,
)
from .entity import IDeEntity
from .entity import _build_entity_unique_id as _build_entity_unique_id_v3
from .sensor import AccumulatedConsumption, HistoricalConsumption

_LOGGER = logging.getLogger(__name__)

SensorType = Type["IDeEntity"]
SensorType = type[IDeEntity]


def update_integration(
Expand Down

0 comments on commit 3509f3e

Please sign in to comment.