Update black to 22.1.0 (#65788)

This commit is contained in:
Franck Nijhof 2022-02-05 14:19:37 +01:00 committed by GitHub
parent 58409d0895
commit fa09cf663e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 204 additions and 255 deletions

View file

@ -5,7 +5,7 @@ repos:
- id: pyupgrade - id: pyupgrade
args: [--py39-plus] args: [--py39-plus]
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 21.12b0 rev: 22.1.0
hooks: hooks:
- id: black - id: black
args: args:

View file

@ -242,7 +242,7 @@ class AppleTVManager:
backoff = min( backoff = min(
max( max(
BACKOFF_TIME_LOWER_LIMIT, BACKOFF_TIME_LOWER_LIMIT,
randrange(2 ** self._connection_attempts), randrange(2**self._connection_attempts),
), ),
BACKOFF_TIME_UPPER_LIMIT, BACKOFF_TIME_UPPER_LIMIT,
) )

View file

@ -260,7 +260,7 @@ CC_SENSOR_TYPES = (
name="Particulate Matter < 2.5 μm", name="Particulate Matter < 2.5 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3, metric_conversion=3.2808399**3,
is_metric_check=True, is_metric_check=True,
), ),
ClimaCellSensorEntityDescription( ClimaCellSensorEntityDescription(
@ -268,7 +268,7 @@ CC_SENSOR_TYPES = (
name="Particulate Matter < 10 μm", name="Particulate Matter < 10 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3, metric_conversion=3.2808399**3,
is_metric_check=True, is_metric_check=True,
), ),
ClimaCellSensorEntityDescription( ClimaCellSensorEntityDescription(
@ -424,7 +424,7 @@ CC_V3_SENSOR_TYPES = (
name="Particulate Matter < 2.5 μm", name="Particulate Matter < 2.5 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3, metric_conversion=3.2808399**3,
is_metric_check=False, is_metric_check=False,
), ),
ClimaCellSensorEntityDescription( ClimaCellSensorEntityDescription(
@ -432,7 +432,7 @@ CC_V3_SENSOR_TYPES = (
name="Particulate Matter < 10 μm", name="Particulate Matter < 10 μm",
unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT,
unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
metric_conversion=3.2808399 ** 3, metric_conversion=3.2808399**3,
is_metric_check=False, is_metric_check=False,
), ),
ClimaCellSensorEntityDescription( ClimaCellSensorEntityDescription(

View file

@ -24,11 +24,11 @@ def create_matcher(utterance):
# Group part # Group part
if group_match is not None: if group_match is not None:
pattern.append(fr"(?P<{group_match.groups()[0]}>[\w ]+?)\s*") pattern.append(rf"(?P<{group_match.groups()[0]}>[\w ]+?)\s*")
# Optional part # Optional part
elif optional_match is not None: elif optional_match is not None:
pattern.append(fr"(?:{optional_match.groups()[0]} *)?") pattern.append(rf"(?:{optional_match.groups()[0]} *)?")
pattern.append("$") pattern.append("$")
return re.compile("".join(pattern), re.I) return re.compile("".join(pattern), re.I)

View file

@ -75,7 +75,7 @@ class CPUSpeedSensor(SensorEntity):
info = cpuinfo.get_cpu_info() info = cpuinfo.get_cpu_info()
if info and HZ_ACTUAL in info: if info and HZ_ACTUAL in info:
self._attr_native_value = round(float(info[HZ_ACTUAL][0]) / 10 ** 9, 2) self._attr_native_value = round(float(info[HZ_ACTUAL][0]) / 10**9, 2)
else: else:
self._attr_native_value = None self._attr_native_value = None
@ -86,5 +86,5 @@ class CPUSpeedSensor(SensorEntity):
} }
if HZ_ADVERTISED in info: if HZ_ADVERTISED in info:
self._attr_extra_state_attributes[ATTR_HZ] = round( self._attr_extra_state_attributes[ATTR_HZ] = round(
info[HZ_ADVERTISED][0] / 10 ** 9, 2 info[HZ_ADVERTISED][0] / 10**9, 2
) )

View file

@ -168,7 +168,7 @@ class EnOceanPowerSensor(EnOceanSensor):
# this packet reports the current value # this packet reports the current value
raw_val = packet.parsed["MR"]["raw_value"] raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"] divisor = packet.parsed["DIV"]["raw_value"]
self._attr_native_value = raw_val / (10 ** divisor) self._attr_native_value = raw_val / (10**divisor)
self.schedule_update_ha_state() self.schedule_update_ha_state()

View file

@ -91,7 +91,7 @@ class EnOceanSwitch(EnOceanEntity, SwitchEntity):
if packet.parsed["DT"]["raw_value"] == 1: if packet.parsed["DT"]["raw_value"] == 1:
raw_val = packet.parsed["MR"]["raw_value"] raw_val = packet.parsed["MR"]["raw_value"]
divisor = packet.parsed["DIV"]["raw_value"] divisor = packet.parsed["DIV"]["raw_value"]
watts = raw_val / (10 ** divisor) watts = raw_val / (10**divisor)
if watts > 1: if watts > 1:
self._on_state = True self._on_state = True
self.schedule_update_ha_state() self.schedule_update_ha_state()

View file

@ -65,7 +65,7 @@ class BanSensor(SensorEntity):
self.last_ban = None self.last_ban = None
self.log_parser = log_parser self.log_parser = log_parser
self.log_parser.ip_regex[self.jail] = re.compile( self.log_parser.ip_regex[self.jail] = re.compile(
fr"\[{re.escape(self.jail)}\]\s*(Ban|Unban) (.*)" rf"\[{re.escape(self.jail)}\]\s*(Ban|Unban) (.*)"
) )
_LOGGER.debug("Setting up jail %s", self.jail) _LOGGER.debug("Setting up jail %s", self.jail)

View file

@ -158,12 +158,9 @@ def wifi_entities_list(
if network_info: if network_info:
ssid = network_info["NewSSID"] ssid = network_info["NewSSID"]
_LOGGER.debug("SSID from device: <%s>", ssid) _LOGGER.debug("SSID from device: <%s>", ssid)
if ( if slugify(
slugify( ssid,
ssid, ) in [slugify(v) for v in networks.values()]:
)
in [slugify(v) for v in networks.values()]
):
_LOGGER.debug("SSID duplicated, adding suffix") _LOGGER.debug("SSID duplicated, adding suffix")
networks[i] = f'{ssid} {std_table[network_info["NewStandard"]]}' networks[i] = f'{ssid} {std_table[network_info["NewStandard"]]}'
else: else:

View file

@ -19,7 +19,7 @@ DEFAULT_SCAN_INTERVAL = 60
DATA_UPDATED = "glances_data_updated" DATA_UPDATED = "glances_data_updated"
SUPPORTED_VERSIONS = [2, 3] SUPPORTED_VERSIONS = [2, 3]
if sys.maxsize > 2 ** 32: if sys.maxsize > 2**32:
CPU_ICON = "mdi:cpu-64-bit" CPU_ICON = "mdi:cpu-64-bit"
else: else:
CPU_ICON = "mdi:cpu-32-bit" CPU_ICON = "mdi:cpu-32-bit"

View file

@ -129,14 +129,14 @@ class GlancesSensor(SensorEntity):
break break
if self.entity_description.key == "disk_free": if self.entity_description.key == "disk_free":
try: try:
self._state = round(disk["free"] / 1024 ** 3, 1) self._state = round(disk["free"] / 1024**3, 1)
except KeyError: except KeyError:
self._state = round( self._state = round(
(disk["size"] - disk["used"]) / 1024 ** 3, (disk["size"] - disk["used"]) / 1024**3,
1, 1,
) )
elif self.entity_description.key == "disk_use": elif self.entity_description.key == "disk_use":
self._state = round(disk["used"] / 1024 ** 3, 1) self._state = round(disk["used"] / 1024**3, 1)
elif self.entity_description.key == "disk_use_percent": elif self.entity_description.key == "disk_use_percent":
self._state = disk["percent"] self._state = disk["percent"]
elif self.entity_description.key == "battery": elif self.entity_description.key == "battery":
@ -170,15 +170,15 @@ class GlancesSensor(SensorEntity):
elif self.entity_description.key == "memory_use_percent": elif self.entity_description.key == "memory_use_percent":
self._state = value["mem"]["percent"] self._state = value["mem"]["percent"]
elif self.entity_description.key == "memory_use": elif self.entity_description.key == "memory_use":
self._state = round(value["mem"]["used"] / 1024 ** 2, 1) self._state = round(value["mem"]["used"] / 1024**2, 1)
elif self.entity_description.key == "memory_free": elif self.entity_description.key == "memory_free":
self._state = round(value["mem"]["free"] / 1024 ** 2, 1) self._state = round(value["mem"]["free"] / 1024**2, 1)
elif self.entity_description.key == "swap_use_percent": elif self.entity_description.key == "swap_use_percent":
self._state = value["memswap"]["percent"] self._state = value["memswap"]["percent"]
elif self.entity_description.key == "swap_use": elif self.entity_description.key == "swap_use":
self._state = round(value["memswap"]["used"] / 1024 ** 3, 1) self._state = round(value["memswap"]["used"] / 1024**3, 1)
elif self.entity_description.key == "swap_free": elif self.entity_description.key == "swap_free":
self._state = round(value["memswap"]["free"] / 1024 ** 3, 1) self._state = round(value["memswap"]["free"] / 1024**3, 1)
elif self.entity_description.key == "processor_load": elif self.entity_description.key == "processor_load":
# Windows systems don't provide load details # Windows systems don't provide load details
try: try:
@ -219,7 +219,7 @@ class GlancesSensor(SensorEntity):
for container in value["docker"]["containers"]: for container in value["docker"]["containers"]:
if container["Status"] == "running" or "Up" in container["Status"]: if container["Status"] == "running" or "Up" in container["Status"]:
mem_use += container["memory"]["usage"] mem_use += container["memory"]["usage"]
self._state = round(mem_use / 1024 ** 2, 1) self._state = round(mem_use / 1024**2, 1)
except KeyError: except KeyError:
self._state = STATE_UNAVAILABLE self._state = STATE_UNAVAILABLE
elif self.entity_description.type == "raid": elif self.entity_description.type == "raid":

View file

@ -774,14 +774,10 @@ class StartStopTrait(_Trait):
"""Execute a StartStop command.""" """Execute a StartStop command."""
if command == COMMAND_STARTSTOP: if command == COMMAND_STARTSTOP:
if params["start"] is False: if params["start"] is False:
if ( if self.state.state in (
self.state.state cover.STATE_CLOSING,
in ( cover.STATE_OPENING,
cover.STATE_CLOSING, ) or self.state.attributes.get(ATTR_ASSUMED_STATE):
cover.STATE_OPENING,
)
or self.state.attributes.get(ATTR_ASSUMED_STATE)
):
await self.hass.services.async_call( await self.hass.services.async_call(
self.state.domain, self.state.domain,
cover.SERVICE_STOP_COVER, cover.SERVICE_STOP_COVER,

View file

@ -119,14 +119,10 @@ def get_accessory(hass, driver, state, aid, config): # noqa: C901
elif state.domain == "cover": elif state.domain == "cover":
device_class = state.attributes.get(ATTR_DEVICE_CLASS) device_class = state.attributes.get(ATTR_DEVICE_CLASS)
if ( if device_class in (
device_class cover.CoverDeviceClass.GARAGE,
in ( cover.CoverDeviceClass.GATE,
cover.CoverDeviceClass.GARAGE, ) and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE):
cover.CoverDeviceClass.GATE,
)
and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE)
):
a_type = "GarageDoorOpener" a_type = "GarageDoorOpener"
elif ( elif (
device_class == cover.CoverDeviceClass.WINDOW device_class == cover.CoverDeviceClass.WINDOW

View file

@ -59,7 +59,7 @@ DEFAULT_DEVELOPMENT: Final = "0"
DEFAULT_CORS: Final[list[str]] = ["https://cast.home-assistant.io"] DEFAULT_CORS: Final[list[str]] = ["https://cast.home-assistant.io"]
NO_LOGIN_ATTEMPT_THRESHOLD: Final = -1 NO_LOGIN_ATTEMPT_THRESHOLD: Final = -1
MAX_CLIENT_SIZE: Final = 1024 ** 2 * 16 MAX_CLIENT_SIZE: Final = 1024**2 * 16
STORAGE_KEY: Final = DOMAIN STORAGE_KEY: Final = DOMAIN
STORAGE_VERSION: Final = 1 STORAGE_VERSION: Final = 1

View file

@ -49,7 +49,7 @@ RIGHT_METHOD = "right"
INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD] INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD]
# SI Metric prefixes # SI Metric prefixes
UNIT_PREFIXES = {None: 1, "k": 10 ** 3, "M": 10 ** 6, "G": 10 ** 9, "T": 10 ** 12} UNIT_PREFIXES = {None: 1, "k": 10**3, "M": 10**6, "G": 10**9, "T": 10**12}
# SI Time prefixes # SI Time prefixes
UNIT_TIME = { UNIT_TIME = {

View file

@ -130,7 +130,7 @@ def numeric_type_validator(value: Any) -> str | int:
def _max_payload_value(payload_length: int) -> int: def _max_payload_value(payload_length: int) -> int:
if payload_length == 0: if payload_length == 0:
return 0x3F return 0x3F
return int(256 ** payload_length) - 1 return int(256**payload_length) - 1
def button_payload_sub_validator(entity_config: OrderedDict) -> OrderedDict: def button_payload_sub_validator(entity_config: OrderedDict) -> OrderedDict:

View file

@ -76,7 +76,7 @@ class UsageSensor(LTESensor):
@property @property
def native_value(self): def native_value(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return round(self.modem_data.data.usage / 1024 ** 2, 1) return round(self.modem_data.data.usage / 1024**2, 1)
class GenericSensor(LTESensor): class GenericSensor(LTESensor):

View file

@ -126,7 +126,7 @@ class NZBGetSensor(NZBGetEntity, SensorEntity):
if "DownloadRate" in sensor_type and value > 0: if "DownloadRate" in sensor_type and value > 0:
# Convert download rate from Bytes/s to MBytes/s # Convert download rate from Bytes/s to MBytes/s
return round(value / 2 ** 20, 2) return round(value / 2**20, 2)
if "UpTimeSec" in sensor_type and value > 0: if "UpTimeSec" in sensor_type and value > 0:
uptime = utcnow() - timedelta(seconds=value) uptime = utcnow() - timedelta(seconds=value)

View file

@ -253,7 +253,7 @@ class PandoraMediaPlayer(MediaPlayerEntity):
try: try:
match_idx = self._pianobar.expect( match_idx = self._pianobar.expect(
[ [
br"(\d\d):(\d\d)/(\d\d):(\d\d)", rb"(\d\d):(\d\d)/(\d\d):(\d\d)",
"No song playing", "No song playing",
"Select station", "Select station",
"Receiving new playlist", "Receiving new playlist",

View file

@ -132,7 +132,7 @@ class PyLoadSensor(SensorEntity):
if "speed" in self.type and value > 0: if "speed" in self.type and value > 0:
# Convert download rate from Bytes/s to MBytes/s # Convert download rate from Bytes/s to MBytes/s
self._state = round(value / 2 ** 20, 2) self._state = round(value / 2**20, 2)
else: else:
self._state = value self._state = value

View file

@ -167,8 +167,8 @@ class SonarrSensor(SonarrEntity, SensorEntity):
if key == "diskspace": if key == "diskspace":
for disk in self.sonarr.app.disks: for disk in self.sonarr.app.disks:
free = disk.free / 1024 ** 3 free = disk.free / 1024**3
total = disk.total / 1024 ** 3 total = disk.total / 1024**3
usage = free / total * 100 usage = free / total * 100
attrs[ attrs[
@ -203,7 +203,7 @@ class SonarrSensor(SonarrEntity, SensorEntity):
if key == "diskspace": if key == "diskspace":
total_free = sum(disk.free for disk in self.sonarr.app.disks) total_free = sum(disk.free for disk in self.sonarr.app.disks)
free = total_free / 1024 ** 3 free = total_free / 1024**3
return f"{free:.2f}" return f"{free:.2f}"
if key == "commands" and self.data.get(key) is not None: if key == "commands" and self.data.get(key) is not None:

View file

@ -36,14 +36,14 @@ SENSOR_TYPES: Final[tuple[SpeedtestSensorEntityDescription, ...]] = (
name="Download", name="Download",
native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND, native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
value=lambda value: round(value / 10 ** 6, 2), value=lambda value: round(value / 10**6, 2),
), ),
SpeedtestSensorEntityDescription( SpeedtestSensorEntityDescription(
key="upload", key="upload",
name="Upload", name="Upload",
native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND, native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
value=lambda value: round(value / 10 ** 6, 2), value=lambda value: round(value / 10**6, 2),
), ),
) )

View file

@ -194,7 +194,7 @@ class StartcaData:
:param value: The value in bytes to convert to GB. :param value: The value in bytes to convert to GB.
:return: Converted GB value :return: Converted GB value
""" """
return float(value) * 10 ** -9 return float(value) * 10**-9
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self): async def async_update(self):

View file

@ -105,7 +105,7 @@ class SynoDSMUtilSensor(SynoDSMSensor):
# Data (RAM) # Data (RAM)
if self.native_unit_of_measurement == DATA_MEGABYTES: if self.native_unit_of_measurement == DATA_MEGABYTES:
return round(attr / 1024.0 ** 2, 1) return round(attr / 1024.0**2, 1)
# Network # Network
if self.native_unit_of_measurement == DATA_RATE_KILOBYTES_PER_SECOND: if self.native_unit_of_measurement == DATA_RATE_KILOBYTES_PER_SECOND:
@ -147,7 +147,7 @@ class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor):
# Data (disk space) # Data (disk space)
if self.native_unit_of_measurement == DATA_TERABYTES: if self.native_unit_of_measurement == DATA_TERABYTES:
return round(attr / 1024.0 ** 4, 2) return round(attr / 1024.0**4, 2)
return attr return attr

View file

@ -104,7 +104,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=DATA_GIGABYTES, native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory", icon="mdi:memory",
value=lambda bridge: round(bridge.memory.free / 1000 ** 3, 2), value=lambda bridge: round(bridge.memory.free / 1000**3, 2),
), ),
SystemBridgeSensorEntityDescription( SystemBridgeSensorEntityDescription(
key="memory_used_percentage", key="memory_used_percentage",
@ -121,7 +121,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = (
state_class=SensorStateClass.MEASUREMENT, state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=DATA_GIGABYTES, native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory", icon="mdi:memory",
value=lambda bridge: round(bridge.memory.used / 1000 ** 3, 2), value=lambda bridge: round(bridge.memory.used / 1000**3, 2),
), ),
SystemBridgeSensorEntityDescription( SystemBridgeSensorEntityDescription(
key="os", key="os",
@ -324,7 +324,7 @@ async def async_setup_entry(
native_unit_of_measurement=DATA_GIGABYTES, native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory", icon="mdi:memory",
value=lambda bridge, i=index: round( value=lambda bridge, i=index: round(
bridge.graphics.controllers[i].memoryFree / 10 ** 3, 2 bridge.graphics.controllers[i].memoryFree / 10**3, 2
), ),
), ),
), ),
@ -356,7 +356,7 @@ async def async_setup_entry(
native_unit_of_measurement=DATA_GIGABYTES, native_unit_of_measurement=DATA_GIGABYTES,
icon="mdi:memory", icon="mdi:memory",
value=lambda bridge, i=index: round( value=lambda bridge, i=index: round(
bridge.graphics.controllers[i].memoryUsed / 10 ** 3, 2 bridge.graphics.controllers[i].memoryUsed / 10**3, 2
), ),
), ),
), ),

View file

@ -51,7 +51,7 @@ _LOGGER = logging.getLogger(__name__)
CONF_ARG = "arg" CONF_ARG = "arg"
if sys.maxsize > 2 ** 32: if sys.maxsize > 2**32:
CPU_ICON = "mdi:cpu-64-bit" CPU_ICON = "mdi:cpu-64-bit"
else: else:
CPU_ICON = "mdi:cpu-32-bit" CPU_ICON = "mdi:cpu-32-bit"
@ -473,22 +473,22 @@ def _update( # noqa: C901
if type_ == "disk_use_percent": if type_ == "disk_use_percent":
state = _disk_usage(data.argument).percent state = _disk_usage(data.argument).percent
elif type_ == "disk_use": elif type_ == "disk_use":
state = round(_disk_usage(data.argument).used / 1024 ** 3, 1) state = round(_disk_usage(data.argument).used / 1024**3, 1)
elif type_ == "disk_free": elif type_ == "disk_free":
state = round(_disk_usage(data.argument).free / 1024 ** 3, 1) state = round(_disk_usage(data.argument).free / 1024**3, 1)
elif type_ == "memory_use_percent": elif type_ == "memory_use_percent":
state = _virtual_memory().percent state = _virtual_memory().percent
elif type_ == "memory_use": elif type_ == "memory_use":
virtual_memory = _virtual_memory() virtual_memory = _virtual_memory()
state = round((virtual_memory.total - virtual_memory.available) / 1024 ** 2, 1) state = round((virtual_memory.total - virtual_memory.available) / 1024**2, 1)
elif type_ == "memory_free": elif type_ == "memory_free":
state = round(_virtual_memory().available / 1024 ** 2, 1) state = round(_virtual_memory().available / 1024**2, 1)
elif type_ == "swap_use_percent": elif type_ == "swap_use_percent":
state = _swap_memory().percent state = _swap_memory().percent
elif type_ == "swap_use": elif type_ == "swap_use":
state = round(_swap_memory().used / 1024 ** 2, 1) state = round(_swap_memory().used / 1024**2, 1)
elif type_ == "swap_free": elif type_ == "swap_free":
state = round(_swap_memory().free / 1024 ** 2, 1) state = round(_swap_memory().free / 1024**2, 1)
elif type_ == "processor_use": elif type_ == "processor_use":
state = round(psutil.cpu_percent(interval=None)) state = round(psutil.cpu_percent(interval=None))
elif type_ == "processor_temperature": elif type_ == "processor_temperature":
@ -510,7 +510,7 @@ def _update( # noqa: C901
counters = _net_io_counters() counters = _net_io_counters()
if data.argument in counters: if data.argument in counters:
counter = counters[data.argument][IO_COUNTER[type_]] counter = counters[data.argument][IO_COUNTER[type_]]
state = round(counter / 1024 ** 2, 1) state = round(counter / 1024**2, 1)
else: else:
state = None state = None
elif type_ in ("packets_out", "packets_in"): elif type_ in ("packets_out", "packets_in"):
@ -527,7 +527,7 @@ def _update( # noqa: C901
if data.value and data.value < counter: if data.value and data.value < counter:
state = round( state = round(
(counter - data.value) (counter - data.value)
/ 1000 ** 2 / 1000**2
/ (now - (data.update_time or now)).total_seconds(), / (now - (data.update_time or now)).total_seconds(),
3, 3,
) )

View file

@ -45,11 +45,11 @@ class IntegerTypeData:
def scale_value(self, value: float | int) -> float: def scale_value(self, value: float | int) -> float:
"""Scale a value.""" """Scale a value."""
return value * 1.0 / (10 ** self.scale) return value * 1.0 / (10**self.scale)
def scale_value_back(self, value: float | int) -> int: def scale_value_back(self, value: float | int) -> int:
"""Return raw value for scaled.""" """Return raw value for scaled."""
return int(value * (10 ** self.scale)) return int(value * (10**self.scale))
def remap_value_to( def remap_value_to(
self, self,

View file

@ -91,15 +91,11 @@ async def async_setup_platform(
_LOGGER.debug("The following stations were returned: %s", stations) _LOGGER.debug("The following stations were returned: %s", stations)
for station in stations: for station in stations:
waqi_sensor = WaqiSensor(client, station) waqi_sensor = WaqiSensor(client, station)
if ( if not station_filter or {
not station_filter waqi_sensor.uid,
or { waqi_sensor.url,
waqi_sensor.uid, waqi_sensor.station_name,
waqi_sensor.url, } & set(station_filter):
waqi_sensor.station_name,
}
& set(station_filter)
):
dev.append(waqi_sensor) dev.append(waqi_sensor)
except ( except (
aiohttp.client_exceptions.ClientConnectorError, aiohttp.client_exceptions.ClientConnectorError,

View file

@ -431,14 +431,10 @@ class Thermostat(ZhaEntity, ClimateEntity):
self.debug("preset mode '%s' is not supported", preset_mode) self.debug("preset mode '%s' is not supported", preset_mode)
return return
if ( if self.preset_mode not in (
self.preset_mode preset_mode,
not in ( PRESET_NONE,
preset_mode, ) and not await self.async_preset_handler(self.preset_mode, enable=False):
PRESET_NONE,
)
and not await self.async_preset_handler(self.preset_mode, enable=False)
):
self.debug("Couldn't turn off '%s' preset", self.preset_mode) self.debug("Couldn't turn off '%s' preset", self.preset_mode)
return return

View file

@ -1919,7 +1919,7 @@ def _async_create_timer(hass: HomeAssistant) -> None:
"""Schedule a timer tick when the next second rolls around.""" """Schedule a timer tick when the next second rolls around."""
nonlocal handle nonlocal handle
slp_seconds = 1 - (now.microsecond / 10 ** 6) slp_seconds = 1 - (now.microsecond / 10**6)
target = monotonic() + slp_seconds target = monotonic() + slp_seconds
handle = hass.loop.call_later(slp_seconds, fire_time_event, target) handle = hass.loop.call_later(slp_seconds, fire_time_event, target)

View file

@ -42,5 +42,5 @@ def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]:
Async friendly. Async friendly.
""" """
pattern = re.compile(fr"^{domain}(| .+)$") pattern = re.compile(rf"^{domain}(| .+)$")
return [key for key in config.keys() if pattern.match(key)] return [key for key in config.keys() if pattern.match(key)]

View file

@ -1302,7 +1302,7 @@ def forgiving_round(value, precision=0, method="common", default=_SENTINEL):
"""Filter to round a value.""" """Filter to round a value."""
try: try:
# support rounding methods like jinja # support rounding methods like jinja
multiplier = float(10 ** precision) multiplier = float(10**precision)
if method == "ceil": if method == "ceil":
value = math.ceil(float(value) * multiplier) / multiplier value = math.ceil(float(value) * multiplier) / multiplier
elif method == "floor": elif method == "floor":

View file

@ -65,7 +65,7 @@ async def fire_events(hass):
"""Fire a million events.""" """Fire a million events."""
count = 0 count = 0
event_name = "benchmark_event" event_name = "benchmark_event"
events_to_fire = 10 ** 6 events_to_fire = 10**6
@core.callback @core.callback
def listener(_): def listener(_):
@ -92,7 +92,7 @@ async def fire_events_with_filter(hass):
"""Fire a million events with a filter that rejects them.""" """Fire a million events with a filter that rejects them."""
count = 0 count = 0
event_name = "benchmark_event" event_name = "benchmark_event"
events_to_fire = 10 ** 6 events_to_fire = 10**6
@core.callback @core.callback
def event_filter(event): def event_filter(event):
@ -131,13 +131,13 @@ async def time_changed_helper(hass):
nonlocal count nonlocal count
count += 1 count += 1
if count == 10 ** 6: if count == 10**6:
event.set() event.set()
hass.helpers.event.async_track_time_change(listener, minute=0, second=0) hass.helpers.event.async_track_time_change(listener, minute=0, second=0)
event_data = {ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)} event_data = {ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)}
for _ in range(10 ** 6): for _ in range(10**6):
hass.bus.async_fire(EVENT_TIME_CHANGED, event_data) hass.bus.async_fire(EVENT_TIME_CHANGED, event_data)
start = timer() start = timer()
@ -160,7 +160,7 @@ async def state_changed_helper(hass):
nonlocal count nonlocal count
count += 1 count += 1
if count == 10 ** 6: if count == 10**6:
event.set() event.set()
for idx in range(1000): for idx in range(1000):
@ -173,7 +173,7 @@ async def state_changed_helper(hass):
"new_state": core.State(entity_id, "on"), "new_state": core.State(entity_id, "on"),
} }
for _ in range(10 ** 6): for _ in range(10**6):
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data) hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
start = timer() start = timer()
@ -188,7 +188,7 @@ async def state_changed_event_helper(hass):
"""Run a million events through state changed event helper with 1000 entities.""" """Run a million events through state changed event helper with 1000 entities."""
count = 0 count = 0
entity_id = "light.kitchen" entity_id = "light.kitchen"
events_to_fire = 10 ** 6 events_to_fire = 10**6
@core.callback @core.callback
def listener(*args): def listener(*args):
@ -223,7 +223,7 @@ async def state_changed_event_filter_helper(hass):
"""Run a million events through state changed event helper with 1000 entities that all get filtered.""" """Run a million events through state changed event helper with 1000 entities that all get filtered."""
count = 0 count = 0
entity_id = "light.kitchen" entity_id = "light.kitchen"
events_to_fire = 10 ** 6 events_to_fire = 10**6
@core.callback @core.callback
def listener(*args): def listener(*args):
@ -292,7 +292,7 @@ async def _logbook_filtering(hass, last_changed, last_updated):
) )
def yield_events(event): def yield_events(event):
for _ in range(10 ** 5): for _ in range(10**5):
# pylint: disable=protected-access # pylint: disable=protected-access
if logbook._keep_event(hass, event, entities_filter): if logbook._keep_event(hass, event, entities_filter):
yield event yield event
@ -363,7 +363,7 @@ async def filtering_entity_id(hass):
start = timer() start = timer()
for i in range(10 ** 5): for i in range(10**5):
entities_filter(entity_ids[i % size]) entities_filter(entity_ids[i % size])
return timer() - start return timer() - start
@ -373,7 +373,7 @@ async def filtering_entity_id(hass):
async def valid_entity_id(hass): async def valid_entity_id(hass):
"""Run valid entity ID a million times.""" """Run valid entity ID a million times."""
start = timer() start = timer()
for _ in range(10 ** 6): for _ in range(10**6):
core.valid_entity_id("light.kitchen") core.valid_entity_id("light.kitchen")
return timer() - start return timer() - start
@ -383,7 +383,7 @@ async def json_serialize_states(hass):
"""Serialize million states with websocket default encoder.""" """Serialize million states with websocket default encoder."""
states = [ states = [
core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"}) core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"})
for _ in range(10 ** 6) for _ in range(10**6)
] ]
start = timer() start = timer()

View file

@ -115,7 +115,7 @@ def vincenty(
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda
sigma = math.atan2(sinSigma, cosSigma) sigma = math.atan2(sinSigma, cosSigma)
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma
cosSqAlpha = 1 - sinAlpha ** 2 cosSqAlpha = 1 - sinAlpha**2
try: try:
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha
except ZeroDivisionError: except ZeroDivisionError:
@ -124,14 +124,14 @@ def vincenty(
LambdaPrev = Lambda LambdaPrev = Lambda
Lambda = L + (1 - C) * FLATTENING * sinAlpha * ( Lambda = L + (1 - C) * FLATTENING * sinAlpha * (
sigma sigma
+ C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM ** 2)) + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM**2))
) )
if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD: if abs(Lambda - LambdaPrev) < CONVERGENCE_THRESHOLD:
break # successful convergence break # successful convergence
else: else:
return None # failure to converge return None # failure to converge
uSq = cosSqAlpha * (AXIS_A ** 2 - AXIS_B ** 2) / (AXIS_B ** 2) uSq = cosSqAlpha * (AXIS_A**2 - AXIS_B**2) / (AXIS_B**2)
A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))
B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))
deltaSigma = ( deltaSigma = (
@ -142,12 +142,12 @@ def vincenty(
+ B + B
/ 4 / 4
* ( * (
cosSigma * (-1 + 2 * cos2SigmaM ** 2) cosSigma * (-1 + 2 * cos2SigmaM**2)
- B - B
/ 6 / 6
* cos2SigmaM * cos2SigmaM
* (-3 + 4 * sinSigma ** 2) * (-3 + 4 * sinSigma**2)
* (-3 + 4 * cos2SigmaM ** 2) * (-3 + 4 * cos2SigmaM**2)
) )
) )
) )

View file

@ -1,7 +1,7 @@
# Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit # Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit
bandit==1.7.0 bandit==1.7.0
black==21.12b0 black==22.1.0
codespell==2.1.0 codespell==2.1.0
flake8-comprehensions==3.7.0 flake8-comprehensions==3.7.0
flake8-docstrings==1.6.0 flake8-docstrings==1.6.0

View file

@ -118,18 +118,15 @@ def test_blueprint_validate():
is None is None
) )
assert ( assert models.Blueprint(
models.Blueprint( {
{ "blueprint": {
"blueprint": { "name": "Hello",
"name": "Hello", "domain": "automation",
"domain": "automation", "homeassistant": {"min_version": "100000.0.0"},
"homeassistant": {"min_version": "100000.0.0"}, },
}, }
} ).validate() == ["Requires at least Home Assistant 100000.0.0"]
).validate()
== ["Requires at least Home Assistant 100000.0.0"]
)
def test_blueprint_inputs(blueprint_2): def test_blueprint_inputs(blueprint_2):

View file

@ -1810,54 +1810,51 @@ async def test_extract_entities():
async def test_extract_devices(): async def test_extract_devices():
"""Test extracting devices.""" """Test extracting devices."""
assert ( assert condition.async_extract_devices(
condition.async_extract_devices( {
{ "condition": "and",
"condition": "and", "conditions": [
"conditions": [ {"condition": "device", "device_id": "abcd", "domain": "light"},
{"condition": "device", "device_id": "abcd", "domain": "light"}, {"condition": "device", "device_id": "qwer", "domain": "switch"},
{"condition": "device", "device_id": "qwer", "domain": "switch"}, {
{ "condition": "state",
"condition": "state", "entity_id": "sensor.not_a_device",
"entity_id": "sensor.not_a_device", "state": "100",
"state": "100", },
}, {
{ "condition": "not",
"condition": "not", "conditions": [
"conditions": [ {
{ "condition": "device",
"condition": "device", "device_id": "abcd_not",
"device_id": "abcd_not", "domain": "light",
"domain": "light", },
}, {
{ "condition": "device",
"condition": "device", "device_id": "qwer_not",
"device_id": "qwer_not", "domain": "switch",
"domain": "switch", },
}, ],
], },
}, {
{ "condition": "or",
"condition": "or", "conditions": [
"conditions": [ {
{ "condition": "device",
"condition": "device", "device_id": "abcd_or",
"device_id": "abcd_or", "domain": "light",
"domain": "light", },
}, {
{ "condition": "device",
"condition": "device", "device_id": "qwer_or",
"device_id": "qwer_or", "domain": "switch",
"domain": "switch", },
}, ],
], },
}, Template("{{ is_state('light.example', 'on') }}"),
Template("{{ is_state('light.example', 'on') }}"), ],
], }
} ) == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"}
)
== {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"}
)
async def test_condition_template_error(hass): async def test_condition_template_error(hass):

View file

@ -1050,23 +1050,20 @@ async def test_component_config_exceptions(hass, caplog):
# component.PLATFORM_SCHEMA # component.PLATFORM_SCHEMA
caplog.clear() caplog.clear()
assert ( assert await config_util.async_process_component_config(
await config_util.async_process_component_config( hass,
hass, {"test_domain": {"platform": "test_platform"}},
{"test_domain": {"platform": "test_platform"}}, integration=Mock(
integration=Mock( domain="test_domain",
domain="test_domain", get_platform=Mock(return_value=None),
get_platform=Mock(return_value=None), get_component=Mock(
get_component=Mock( return_value=Mock(
return_value=Mock( spec=["PLATFORM_SCHEMA_BASE"],
spec=["PLATFORM_SCHEMA_BASE"], PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")),
PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")), )
)
),
), ),
) ),
== {"test_domain": []} ) == {"test_domain": []}
)
assert "ValueError: broken" in caplog.text assert "ValueError: broken" in caplog.text
assert ( assert (
"Unknown error validating test_platform platform config with test_domain component platform schema" "Unknown error validating test_platform platform config with test_domain component platform schema"
@ -1085,20 +1082,15 @@ async def test_component_config_exceptions(hass, caplog):
) )
), ),
): ):
assert ( assert await config_util.async_process_component_config(
await config_util.async_process_component_config( hass,
hass, {"test_domain": {"platform": "test_platform"}},
{"test_domain": {"platform": "test_platform"}}, integration=Mock(
integration=Mock( domain="test_domain",
domain="test_domain", get_platform=Mock(return_value=None),
get_platform=Mock(return_value=None), get_component=Mock(return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])),
get_component=Mock( ),
return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"]) ) == {"test_domain": []}
),
),
)
== {"test_domain": []}
)
assert "ValueError: broken" in caplog.text assert "ValueError: broken" in caplog.text
assert ( assert (
"Unknown error validating config for test_platform platform for test_domain component with PLATFORM_SCHEMA" "Unknown error validating config for test_platform platform for test_domain component with PLATFORM_SCHEMA"

View file

@ -21,7 +21,7 @@ RETYPE = type(re.compile(""))
def mock_stream(data): def mock_stream(data):
"""Mock a stream with data.""" """Mock a stream with data."""
protocol = mock.Mock(_reading_paused=False) protocol = mock.Mock(_reading_paused=False)
stream = StreamReader(protocol, limit=2 ** 16) stream = StreamReader(protocol, limit=2**16)
stream.feed_data(data) stream.feed_data(data)
stream.feed_eof() stream.feed_eof()
return stream return stream

View file

@ -461,20 +461,17 @@ def test_rgbww_to_color_temperature():
Temperature values must be in mireds Temperature values must be in mireds
Home Assistant uses rgbcw for rgbww Home Assistant uses rgbcw for rgbww
""" """
assert ( assert color_util.rgbww_to_color_temperature(
color_util.rgbww_to_color_temperature( (
( 0,
0, 0,
0, 0,
0, 255,
255, 0,
0, ),
), 153,
153, 500,
500, ) == (153, 255)
)
== (153, 255)
)
assert color_util.rgbww_to_color_temperature((0, 0, 0, 128, 0), 153, 500) == ( assert color_util.rgbww_to_color_temperature((0, 0, 0, 128, 0), 153, 500) == (
153, 153,
128, 128,
@ -507,15 +504,12 @@ def test_white_levels_to_color_temperature():
Temperature values must be in mireds Temperature values must be in mireds
Home Assistant uses rgbcw for rgbww Home Assistant uses rgbcw for rgbww
""" """
assert ( assert color_util.while_levels_to_color_temperature(
color_util.while_levels_to_color_temperature( 255,
255, 0,
0, 153,
153, 500,
500, ) == (153, 255)
)
== (153, 255)
)
assert color_util.while_levels_to_color_temperature(128, 0, 153, 500) == ( assert color_util.while_levels_to_color_temperature(128, 0, 153, 500) == (
153, 153,
128, 128,

View file

@ -143,21 +143,15 @@ def test_find_unserializable_data():
bad_data = object() bad_data = object()
assert ( assert find_paths_unserializable_data(
find_paths_unserializable_data( [State("mock_domain.mock_entity", "on", {"bad": bad_data})],
[State("mock_domain.mock_entity", "on", {"bad": bad_data})], dump=partial(dumps, cls=MockJSONEncoder),
dump=partial(dumps, cls=MockJSONEncoder), ) == {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data}
)
== {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data}
)
assert ( assert find_paths_unserializable_data(
find_paths_unserializable_data( [Event("bad_event", {"bad_attribute": bad_data})],
[Event("bad_event", {"bad_attribute": bad_data})], dump=partial(dumps, cls=MockJSONEncoder),
dump=partial(dumps, cls=MockJSONEncoder), ) == {"$[0](Event: bad_event).data.bad_attribute": bad_data}
)
== {"$[0](Event: bad_event).data.bad_attribute": bad_data}
)
class BadData: class BadData:
def __init__(self): def __init__(self):
@ -166,10 +160,7 @@ def test_find_unserializable_data():
def as_dict(self): def as_dict(self):
return {"bla": self.bla} return {"bla": self.bla}
assert ( assert find_paths_unserializable_data(
find_paths_unserializable_data( BadData(),
BadData(), dump=partial(dumps, cls=MockJSONEncoder),
dump=partial(dumps, cls=MockJSONEncoder), ) == {"$(BadData).bla": bad_data}
)
== {"$(BadData).bla": bad_data}
)

View file

@ -25,10 +25,7 @@ def test_substitute():
with pytest.raises(UndefinedSubstitution): with pytest.raises(UndefinedSubstitution):
substitute(Input("hello"), {}) substitute(Input("hello"), {})
assert ( assert substitute(
substitute( {"info": [1, Input("hello"), 2, Input("world")]},
{"info": [1, Input("hello"), 2, Input("world")]}, {"hello": 5, "world": 10},
{"hello": 5, "world": 10}, ) == {"info": [1, 5, 2, 10]}
)
== {"info": [1, 5, 2, 10]}
)