diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 72716f15dfd7..f16a65fb4c07 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,7 +5,7 @@ repos: - id: pyupgrade args: [--py39-plus] - repo: https://github.com/psf/black - rev: 21.12b0 + rev: 22.1.0 hooks: - id: black args: diff --git a/homeassistant/components/apple_tv/__init__.py b/homeassistant/components/apple_tv/__init__.py index bd511d84eb53..d61c21972fbe 100644 --- a/homeassistant/components/apple_tv/__init__.py +++ b/homeassistant/components/apple_tv/__init__.py @@ -242,7 +242,7 @@ class AppleTVManager: backoff = min( max( BACKOFF_TIME_LOWER_LIMIT, - randrange(2 ** self._connection_attempts), + randrange(2**self._connection_attempts), ), BACKOFF_TIME_UPPER_LIMIT, ) diff --git a/homeassistant/components/climacell/const.py b/homeassistant/components/climacell/const.py index 69567bf65fc5..7ee804f42f18 100644 --- a/homeassistant/components/climacell/const.py +++ b/homeassistant/components/climacell/const.py @@ -260,7 +260,7 @@ CC_SENSOR_TYPES = ( name="Particulate Matter < 2.5 μm", unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, - metric_conversion=3.2808399 ** 3, + metric_conversion=3.2808399**3, is_metric_check=True, ), ClimaCellSensorEntityDescription( @@ -268,7 +268,7 @@ CC_SENSOR_TYPES = ( name="Particulate Matter < 10 μm", unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, - metric_conversion=3.2808399 ** 3, + metric_conversion=3.2808399**3, is_metric_check=True, ), ClimaCellSensorEntityDescription( @@ -424,7 +424,7 @@ CC_V3_SENSOR_TYPES = ( name="Particulate Matter < 2.5 μm", unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, - metric_conversion=3.2808399 ** 3, + metric_conversion=3.2808399**3, is_metric_check=False, ), ClimaCellSensorEntityDescription( @@ -432,7 +432,7 @@ CC_V3_SENSOR_TYPES = ( name="Particulate Matter < 10 μm", unit_imperial=CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT, unit_metric=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, - metric_conversion=3.2808399 ** 3, + metric_conversion=3.2808399**3, is_metric_check=False, ), ClimaCellSensorEntityDescription( diff --git a/homeassistant/components/conversation/util.py b/homeassistant/components/conversation/util.py index b21b75be9b58..2e931d835a8d 100644 --- a/homeassistant/components/conversation/util.py +++ b/homeassistant/components/conversation/util.py @@ -24,11 +24,11 @@ def create_matcher(utterance): # Group part 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 elif optional_match is not None: - pattern.append(fr"(?:{optional_match.groups()[0]} *)?") + pattern.append(rf"(?:{optional_match.groups()[0]} *)?") pattern.append("$") return re.compile("".join(pattern), re.I) diff --git a/homeassistant/components/cpuspeed/sensor.py b/homeassistant/components/cpuspeed/sensor.py index 86c02ae9ee9d..686a7c13e58a 100644 --- a/homeassistant/components/cpuspeed/sensor.py +++ b/homeassistant/components/cpuspeed/sensor.py @@ -75,7 +75,7 @@ class CPUSpeedSensor(SensorEntity): info = cpuinfo.get_cpu_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: self._attr_native_value = None @@ -86,5 +86,5 @@ class CPUSpeedSensor(SensorEntity): } if HZ_ADVERTISED in info: self._attr_extra_state_attributes[ATTR_HZ] = round( - info[HZ_ADVERTISED][0] / 10 ** 9, 2 + info[HZ_ADVERTISED][0] / 10**9, 2 ) diff --git a/homeassistant/components/enocean/sensor.py b/homeassistant/components/enocean/sensor.py index 87bcd685a1f7..e48f117648ab 100644 --- a/homeassistant/components/enocean/sensor.py +++ b/homeassistant/components/enocean/sensor.py @@ -168,7 +168,7 @@ class EnOceanPowerSensor(EnOceanSensor): # this packet reports the current value raw_val = packet.parsed["MR"]["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() diff --git a/homeassistant/components/enocean/switch.py b/homeassistant/components/enocean/switch.py index b86b68445518..fc788e88d72a 100644 --- a/homeassistant/components/enocean/switch.py +++ b/homeassistant/components/enocean/switch.py @@ -91,7 +91,7 @@ class EnOceanSwitch(EnOceanEntity, SwitchEntity): if packet.parsed["DT"]["raw_value"] == 1: raw_val = packet.parsed["MR"]["raw_value"] divisor = packet.parsed["DIV"]["raw_value"] - watts = raw_val / (10 ** divisor) + watts = raw_val / (10**divisor) if watts > 1: self._on_state = True self.schedule_update_ha_state() diff --git a/homeassistant/components/fail2ban/sensor.py b/homeassistant/components/fail2ban/sensor.py index 1063dfda08af..f74dc7690ca1 100644 --- a/homeassistant/components/fail2ban/sensor.py +++ b/homeassistant/components/fail2ban/sensor.py @@ -65,7 +65,7 @@ class BanSensor(SensorEntity): self.last_ban = None self.log_parser = log_parser 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) diff --git a/homeassistant/components/fritz/switch.py b/homeassistant/components/fritz/switch.py index fec760fbe7aa..59cb75901a2a 100644 --- a/homeassistant/components/fritz/switch.py +++ b/homeassistant/components/fritz/switch.py @@ -158,12 +158,9 @@ def wifi_entities_list( if network_info: ssid = network_info["NewSSID"] _LOGGER.debug("SSID from device: <%s>", ssid) - if ( - slugify( - ssid, - ) - in [slugify(v) for v in networks.values()] - ): + if slugify( + ssid, + ) in [slugify(v) for v in networks.values()]: _LOGGER.debug("SSID duplicated, adding suffix") networks[i] = f'{ssid} {std_table[network_info["NewStandard"]]}' else: diff --git a/homeassistant/components/glances/const.py b/homeassistant/components/glances/const.py index a25ae1b46608..e5a8f1424c2b 100644 --- a/homeassistant/components/glances/const.py +++ b/homeassistant/components/glances/const.py @@ -19,7 +19,7 @@ DEFAULT_SCAN_INTERVAL = 60 DATA_UPDATED = "glances_data_updated" SUPPORTED_VERSIONS = [2, 3] -if sys.maxsize > 2 ** 32: +if sys.maxsize > 2**32: CPU_ICON = "mdi:cpu-64-bit" else: CPU_ICON = "mdi:cpu-32-bit" diff --git a/homeassistant/components/glances/sensor.py b/homeassistant/components/glances/sensor.py index b28ccd86b84f..a907dd1695ad 100644 --- a/homeassistant/components/glances/sensor.py +++ b/homeassistant/components/glances/sensor.py @@ -129,14 +129,14 @@ class GlancesSensor(SensorEntity): break if self.entity_description.key == "disk_free": try: - self._state = round(disk["free"] / 1024 ** 3, 1) + self._state = round(disk["free"] / 1024**3, 1) except KeyError: self._state = round( - (disk["size"] - disk["used"]) / 1024 ** 3, + (disk["size"] - disk["used"]) / 1024**3, 1, ) 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": self._state = disk["percent"] elif self.entity_description.key == "battery": @@ -170,15 +170,15 @@ class GlancesSensor(SensorEntity): elif self.entity_description.key == "memory_use_percent": self._state = value["mem"]["percent"] 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": - 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": self._state = value["memswap"]["percent"] 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": - 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": # Windows systems don't provide load details try: @@ -219,7 +219,7 @@ class GlancesSensor(SensorEntity): for container in value["docker"]["containers"]: if container["Status"] == "running" or "Up" in container["Status"]: mem_use += container["memory"]["usage"] - self._state = round(mem_use / 1024 ** 2, 1) + self._state = round(mem_use / 1024**2, 1) except KeyError: self._state = STATE_UNAVAILABLE elif self.entity_description.type == "raid": diff --git a/homeassistant/components/google_assistant/trait.py b/homeassistant/components/google_assistant/trait.py index 5b3a2db0b805..20191c616685 100644 --- a/homeassistant/components/google_assistant/trait.py +++ b/homeassistant/components/google_assistant/trait.py @@ -774,14 +774,10 @@ class StartStopTrait(_Trait): """Execute a StartStop command.""" if command == COMMAND_STARTSTOP: if params["start"] is False: - if ( - self.state.state - in ( - cover.STATE_CLOSING, - cover.STATE_OPENING, - ) - or self.state.attributes.get(ATTR_ASSUMED_STATE) - ): + if self.state.state in ( + cover.STATE_CLOSING, + cover.STATE_OPENING, + ) or self.state.attributes.get(ATTR_ASSUMED_STATE): await self.hass.services.async_call( self.state.domain, cover.SERVICE_STOP_COVER, diff --git a/homeassistant/components/homekit/accessories.py b/homeassistant/components/homekit/accessories.py index d8d5a16ac507..922c4c52568b 100644 --- a/homeassistant/components/homekit/accessories.py +++ b/homeassistant/components/homekit/accessories.py @@ -119,14 +119,10 @@ def get_accessory(hass, driver, state, aid, config): # noqa: C901 elif state.domain == "cover": device_class = state.attributes.get(ATTR_DEVICE_CLASS) - if ( - device_class - in ( - cover.CoverDeviceClass.GARAGE, - cover.CoverDeviceClass.GATE, - ) - and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE) - ): + if device_class in ( + cover.CoverDeviceClass.GARAGE, + cover.CoverDeviceClass.GATE, + ) and features & (cover.SUPPORT_OPEN | cover.SUPPORT_CLOSE): a_type = "GarageDoorOpener" elif ( device_class == cover.CoverDeviceClass.WINDOW diff --git a/homeassistant/components/http/__init__.py b/homeassistant/components/http/__init__.py index 9e77563f7a2e..bb168fce09fd 100644 --- a/homeassistant/components/http/__init__.py +++ b/homeassistant/components/http/__init__.py @@ -59,7 +59,7 @@ DEFAULT_DEVELOPMENT: Final = "0" DEFAULT_CORS: Final[list[str]] = ["https://cast.home-assistant.io"] 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_VERSION: Final = 1 diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index c95c96c505bb..7a6248254d82 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -49,7 +49,7 @@ RIGHT_METHOD = "right" INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METHOD, RIGHT_METHOD] # 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 UNIT_TIME = { diff --git a/homeassistant/components/knx/schema.py b/homeassistant/components/knx/schema.py index af475e9c380e..c118e56f9e32 100644 --- a/homeassistant/components/knx/schema.py +++ b/homeassistant/components/knx/schema.py @@ -130,7 +130,7 @@ def numeric_type_validator(value: Any) -> str | int: def _max_payload_value(payload_length: int) -> int: if payload_length == 0: return 0x3F - return int(256 ** payload_length) - 1 + return int(256**payload_length) - 1 def button_payload_sub_validator(entity_config: OrderedDict) -> OrderedDict: diff --git a/homeassistant/components/netgear_lte/sensor.py b/homeassistant/components/netgear_lte/sensor.py index de607f2a3c0c..c27c4f43920c 100644 --- a/homeassistant/components/netgear_lte/sensor.py +++ b/homeassistant/components/netgear_lte/sensor.py @@ -76,7 +76,7 @@ class UsageSensor(LTESensor): @property def native_value(self): """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): diff --git a/homeassistant/components/nzbget/sensor.py b/homeassistant/components/nzbget/sensor.py index 42cacfc8ab5f..9e5bd6e4ac95 100644 --- a/homeassistant/components/nzbget/sensor.py +++ b/homeassistant/components/nzbget/sensor.py @@ -126,7 +126,7 @@ class NZBGetSensor(NZBGetEntity, SensorEntity): if "DownloadRate" in sensor_type and value > 0: # 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: uptime = utcnow() - timedelta(seconds=value) diff --git a/homeassistant/components/pandora/media_player.py b/homeassistant/components/pandora/media_player.py index 45e8f55a7904..7866b99221e6 100644 --- a/homeassistant/components/pandora/media_player.py +++ b/homeassistant/components/pandora/media_player.py @@ -253,7 +253,7 @@ class PandoraMediaPlayer(MediaPlayerEntity): try: 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", "Select station", "Receiving new playlist", diff --git a/homeassistant/components/pyload/sensor.py b/homeassistant/components/pyload/sensor.py index 65c33a41ff32..e4bbf7df3d2e 100644 --- a/homeassistant/components/pyload/sensor.py +++ b/homeassistant/components/pyload/sensor.py @@ -132,7 +132,7 @@ class PyLoadSensor(SensorEntity): if "speed" in self.type and value > 0: # Convert download rate from Bytes/s to MBytes/s - self._state = round(value / 2 ** 20, 2) + self._state = round(value / 2**20, 2) else: self._state = value diff --git a/homeassistant/components/sonarr/sensor.py b/homeassistant/components/sonarr/sensor.py index 8911927d7320..91e1eeb32572 100644 --- a/homeassistant/components/sonarr/sensor.py +++ b/homeassistant/components/sonarr/sensor.py @@ -167,8 +167,8 @@ class SonarrSensor(SonarrEntity, SensorEntity): if key == "diskspace": for disk in self.sonarr.app.disks: - free = disk.free / 1024 ** 3 - total = disk.total / 1024 ** 3 + free = disk.free / 1024**3 + total = disk.total / 1024**3 usage = free / total * 100 attrs[ @@ -203,7 +203,7 @@ class SonarrSensor(SonarrEntity, SensorEntity): if key == "diskspace": 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}" if key == "commands" and self.data.get(key) is not None: diff --git a/homeassistant/components/speedtestdotnet/const.py b/homeassistant/components/speedtestdotnet/const.py index 735c656134b2..e2455ad63df0 100644 --- a/homeassistant/components/speedtestdotnet/const.py +++ b/homeassistant/components/speedtestdotnet/const.py @@ -36,14 +36,14 @@ SENSOR_TYPES: Final[tuple[SpeedtestSensorEntityDescription, ...]] = ( name="Download", native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND, state_class=SensorStateClass.MEASUREMENT, - value=lambda value: round(value / 10 ** 6, 2), + value=lambda value: round(value / 10**6, 2), ), SpeedtestSensorEntityDescription( key="upload", name="Upload", native_unit_of_measurement=DATA_RATE_MEGABITS_PER_SECOND, state_class=SensorStateClass.MEASUREMENT, - value=lambda value: round(value / 10 ** 6, 2), + value=lambda value: round(value / 10**6, 2), ), ) diff --git a/homeassistant/components/startca/sensor.py b/homeassistant/components/startca/sensor.py index dc87116914af..042fc33060a3 100644 --- a/homeassistant/components/startca/sensor.py +++ b/homeassistant/components/startca/sensor.py @@ -194,7 +194,7 @@ class StartcaData: :param value: The value in bytes to convert to GB. :return: Converted GB value """ - return float(value) * 10 ** -9 + return float(value) * 10**-9 @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): diff --git a/homeassistant/components/synology_dsm/sensor.py b/homeassistant/components/synology_dsm/sensor.py index 305e6dda4e7c..18014de8c7a1 100644 --- a/homeassistant/components/synology_dsm/sensor.py +++ b/homeassistant/components/synology_dsm/sensor.py @@ -105,7 +105,7 @@ class SynoDSMUtilSensor(SynoDSMSensor): # Data (RAM) if self.native_unit_of_measurement == DATA_MEGABYTES: - return round(attr / 1024.0 ** 2, 1) + return round(attr / 1024.0**2, 1) # Network if self.native_unit_of_measurement == DATA_RATE_KILOBYTES_PER_SECOND: @@ -147,7 +147,7 @@ class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor): # Data (disk space) if self.native_unit_of_measurement == DATA_TERABYTES: - return round(attr / 1024.0 ** 4, 2) + return round(attr / 1024.0**4, 2) return attr diff --git a/homeassistant/components/system_bridge/sensor.py b/homeassistant/components/system_bridge/sensor.py index 9a4f0cc0aa84..c4969e2c14cf 100644 --- a/homeassistant/components/system_bridge/sensor.py +++ b/homeassistant/components/system_bridge/sensor.py @@ -104,7 +104,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = ( state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=DATA_GIGABYTES, icon="mdi:memory", - value=lambda bridge: round(bridge.memory.free / 1000 ** 3, 2), + value=lambda bridge: round(bridge.memory.free / 1000**3, 2), ), SystemBridgeSensorEntityDescription( key="memory_used_percentage", @@ -121,7 +121,7 @@ BASE_SENSOR_TYPES: tuple[SystemBridgeSensorEntityDescription, ...] = ( state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=DATA_GIGABYTES, icon="mdi:memory", - value=lambda bridge: round(bridge.memory.used / 1000 ** 3, 2), + value=lambda bridge: round(bridge.memory.used / 1000**3, 2), ), SystemBridgeSensorEntityDescription( key="os", @@ -324,7 +324,7 @@ async def async_setup_entry( native_unit_of_measurement=DATA_GIGABYTES, icon="mdi:memory", 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, icon="mdi:memory", value=lambda bridge, i=index: round( - bridge.graphics.controllers[i].memoryUsed / 10 ** 3, 2 + bridge.graphics.controllers[i].memoryUsed / 10**3, 2 ), ), ), diff --git a/homeassistant/components/systemmonitor/sensor.py b/homeassistant/components/systemmonitor/sensor.py index bceda1b453a6..7a57c06ef581 100644 --- a/homeassistant/components/systemmonitor/sensor.py +++ b/homeassistant/components/systemmonitor/sensor.py @@ -51,7 +51,7 @@ _LOGGER = logging.getLogger(__name__) CONF_ARG = "arg" -if sys.maxsize > 2 ** 32: +if sys.maxsize > 2**32: CPU_ICON = "mdi:cpu-64-bit" else: CPU_ICON = "mdi:cpu-32-bit" @@ -473,22 +473,22 @@ def _update( # noqa: C901 if type_ == "disk_use_percent": state = _disk_usage(data.argument).percent 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": - 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": state = _virtual_memory().percent elif type_ == "memory_use": 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": - state = round(_virtual_memory().available / 1024 ** 2, 1) + state = round(_virtual_memory().available / 1024**2, 1) elif type_ == "swap_use_percent": state = _swap_memory().percent elif type_ == "swap_use": - state = round(_swap_memory().used / 1024 ** 2, 1) + state = round(_swap_memory().used / 1024**2, 1) elif type_ == "swap_free": - state = round(_swap_memory().free / 1024 ** 2, 1) + state = round(_swap_memory().free / 1024**2, 1) elif type_ == "processor_use": state = round(psutil.cpu_percent(interval=None)) elif type_ == "processor_temperature": @@ -510,7 +510,7 @@ def _update( # noqa: C901 counters = _net_io_counters() if data.argument in counters: counter = counters[data.argument][IO_COUNTER[type_]] - state = round(counter / 1024 ** 2, 1) + state = round(counter / 1024**2, 1) else: state = None elif type_ in ("packets_out", "packets_in"): @@ -527,7 +527,7 @@ def _update( # noqa: C901 if data.value and data.value < counter: state = round( (counter - data.value) - / 1000 ** 2 + / 1000**2 / (now - (data.update_time or now)).total_seconds(), 3, ) diff --git a/homeassistant/components/tuya/base.py b/homeassistant/components/tuya/base.py index 15e57f223e9d..22764f810805 100644 --- a/homeassistant/components/tuya/base.py +++ b/homeassistant/components/tuya/base.py @@ -45,11 +45,11 @@ class IntegerTypeData: def scale_value(self, value: float | int) -> float: """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: """Return raw value for scaled.""" - return int(value * (10 ** self.scale)) + return int(value * (10**self.scale)) def remap_value_to( self, diff --git a/homeassistant/components/waqi/sensor.py b/homeassistant/components/waqi/sensor.py index 8a3b9f046ce3..499233717b60 100644 --- a/homeassistant/components/waqi/sensor.py +++ b/homeassistant/components/waqi/sensor.py @@ -91,15 +91,11 @@ async def async_setup_platform( _LOGGER.debug("The following stations were returned: %s", stations) for station in stations: waqi_sensor = WaqiSensor(client, station) - if ( - not station_filter - or { - waqi_sensor.uid, - waqi_sensor.url, - waqi_sensor.station_name, - } - & set(station_filter) - ): + if not station_filter or { + waqi_sensor.uid, + waqi_sensor.url, + waqi_sensor.station_name, + } & set(station_filter): dev.append(waqi_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, diff --git a/homeassistant/components/zha/climate.py b/homeassistant/components/zha/climate.py index 65de5fd04cc7..b892fc9a67f2 100644 --- a/homeassistant/components/zha/climate.py +++ b/homeassistant/components/zha/climate.py @@ -431,14 +431,10 @@ class Thermostat(ZhaEntity, ClimateEntity): self.debug("preset mode '%s' is not supported", preset_mode) return - if ( - self.preset_mode - not in ( - preset_mode, - PRESET_NONE, - ) - and not await self.async_preset_handler(self.preset_mode, enable=False) - ): + if self.preset_mode not in ( + preset_mode, + 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) return diff --git a/homeassistant/core.py b/homeassistant/core.py index a29067cdb0d6..27906e0401f3 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -1919,7 +1919,7 @@ def _async_create_timer(hass: HomeAssistant) -> None: """Schedule a timer tick when the next second rolls around.""" nonlocal handle - slp_seconds = 1 - (now.microsecond / 10 ** 6) + slp_seconds = 1 - (now.microsecond / 10**6) target = monotonic() + slp_seconds handle = hass.loop.call_later(slp_seconds, fire_time_event, target) diff --git a/homeassistant/helpers/__init__.py b/homeassistant/helpers/__init__.py index f74aec0efe87..281ab3108b63 100644 --- a/homeassistant/helpers/__init__.py +++ b/homeassistant/helpers/__init__.py @@ -42,5 +42,5 @@ def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]: Async friendly. """ - pattern = re.compile(fr"^{domain}(| .+)$") + pattern = re.compile(rf"^{domain}(| .+)$") return [key for key in config.keys() if pattern.match(key)] diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 916d203782ab..d371017a4750 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1302,7 +1302,7 @@ def forgiving_round(value, precision=0, method="common", default=_SENTINEL): """Filter to round a value.""" try: # support rounding methods like jinja - multiplier = float(10 ** precision) + multiplier = float(10**precision) if method == "ceil": value = math.ceil(float(value) * multiplier) / multiplier elif method == "floor": diff --git a/homeassistant/scripts/benchmark/__init__.py b/homeassistant/scripts/benchmark/__init__.py index 1005b48e1ca7..c57d082de61e 100644 --- a/homeassistant/scripts/benchmark/__init__.py +++ b/homeassistant/scripts/benchmark/__init__.py @@ -65,7 +65,7 @@ async def fire_events(hass): """Fire a million events.""" count = 0 event_name = "benchmark_event" - events_to_fire = 10 ** 6 + events_to_fire = 10**6 @core.callback def listener(_): @@ -92,7 +92,7 @@ async def fire_events_with_filter(hass): """Fire a million events with a filter that rejects them.""" count = 0 event_name = "benchmark_event" - events_to_fire = 10 ** 6 + events_to_fire = 10**6 @core.callback def event_filter(event): @@ -131,13 +131,13 @@ async def time_changed_helper(hass): nonlocal count count += 1 - if count == 10 ** 6: + if count == 10**6: event.set() 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)} - for _ in range(10 ** 6): + for _ in range(10**6): hass.bus.async_fire(EVENT_TIME_CHANGED, event_data) start = timer() @@ -160,7 +160,7 @@ async def state_changed_helper(hass): nonlocal count count += 1 - if count == 10 ** 6: + if count == 10**6: event.set() for idx in range(1000): @@ -173,7 +173,7 @@ async def state_changed_helper(hass): "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) 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.""" count = 0 entity_id = "light.kitchen" - events_to_fire = 10 ** 6 + events_to_fire = 10**6 @core.callback 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.""" count = 0 entity_id = "light.kitchen" - events_to_fire = 10 ** 6 + events_to_fire = 10**6 @core.callback def listener(*args): @@ -292,7 +292,7 @@ async def _logbook_filtering(hass, last_changed, last_updated): ) def yield_events(event): - for _ in range(10 ** 5): + for _ in range(10**5): # pylint: disable=protected-access if logbook._keep_event(hass, event, entities_filter): yield event @@ -363,7 +363,7 @@ async def filtering_entity_id(hass): start = timer() - for i in range(10 ** 5): + for i in range(10**5): entities_filter(entity_ids[i % size]) return timer() - start @@ -373,7 +373,7 @@ async def filtering_entity_id(hass): async def valid_entity_id(hass): """Run valid entity ID a million times.""" start = timer() - for _ in range(10 ** 6): + for _ in range(10**6): core.valid_entity_id("light.kitchen") return timer() - start @@ -383,7 +383,7 @@ async def json_serialize_states(hass): """Serialize million states with websocket default encoder.""" states = [ core.State("light.kitchen", "on", {"friendly_name": "Kitchen Lights"}) - for _ in range(10 ** 6) + for _ in range(10**6) ] start = timer() diff --git a/homeassistant/util/location.py b/homeassistant/util/location.py index b967a6a0b1e8..4e76fa32de39 100644 --- a/homeassistant/util/location.py +++ b/homeassistant/util/location.py @@ -115,7 +115,7 @@ def vincenty( cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda sigma = math.atan2(sinSigma, cosSigma) sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma - cosSqAlpha = 1 - sinAlpha ** 2 + cosSqAlpha = 1 - sinAlpha**2 try: cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha except ZeroDivisionError: @@ -124,14 +124,14 @@ def vincenty( LambdaPrev = Lambda Lambda = L + (1 - C) * FLATTENING * sinAlpha * ( 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: break # successful convergence else: 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))) B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) deltaSigma = ( @@ -142,12 +142,12 @@ def vincenty( + B / 4 * ( - cosSigma * (-1 + 2 * cos2SigmaM ** 2) + cosSigma * (-1 + 2 * cos2SigmaM**2) - B / 6 * cos2SigmaM - * (-3 + 4 * sinSigma ** 2) - * (-3 + 4 * cos2SigmaM ** 2) + * (-3 + 4 * sinSigma**2) + * (-3 + 4 * cos2SigmaM**2) ) ) ) diff --git a/requirements_test_pre_commit.txt b/requirements_test_pre_commit.txt index 2e37b2175ba9..ca7828267b6e 100644 --- a/requirements_test_pre_commit.txt +++ b/requirements_test_pre_commit.txt @@ -1,7 +1,7 @@ # Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit bandit==1.7.0 -black==21.12b0 +black==22.1.0 codespell==2.1.0 flake8-comprehensions==3.7.0 flake8-docstrings==1.6.0 diff --git a/tests/components/blueprint/test_models.py b/tests/components/blueprint/test_models.py index ba8914c3b1d9..497e8b36e99e 100644 --- a/tests/components/blueprint/test_models.py +++ b/tests/components/blueprint/test_models.py @@ -118,18 +118,15 @@ def test_blueprint_validate(): is None ) - assert ( - models.Blueprint( - { - "blueprint": { - "name": "Hello", - "domain": "automation", - "homeassistant": {"min_version": "100000.0.0"}, - }, - } - ).validate() - == ["Requires at least Home Assistant 100000.0.0"] - ) + assert models.Blueprint( + { + "blueprint": { + "name": "Hello", + "domain": "automation", + "homeassistant": {"min_version": "100000.0.0"}, + }, + } + ).validate() == ["Requires at least Home Assistant 100000.0.0"] def test_blueprint_inputs(blueprint_2): diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index d958c633b621..e0cc9b715c10 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -1810,54 +1810,51 @@ async def test_extract_entities(): async def test_extract_devices(): """Test extracting devices.""" - assert ( - condition.async_extract_devices( - { - "condition": "and", - "conditions": [ - {"condition": "device", "device_id": "abcd", "domain": "light"}, - {"condition": "device", "device_id": "qwer", "domain": "switch"}, - { - "condition": "state", - "entity_id": "sensor.not_a_device", - "state": "100", - }, - { - "condition": "not", - "conditions": [ - { - "condition": "device", - "device_id": "abcd_not", - "domain": "light", - }, - { - "condition": "device", - "device_id": "qwer_not", - "domain": "switch", - }, - ], - }, - { - "condition": "or", - "conditions": [ - { - "condition": "device", - "device_id": "abcd_or", - "domain": "light", - }, - { - "condition": "device", - "device_id": "qwer_or", - "domain": "switch", - }, - ], - }, - Template("{{ is_state('light.example', 'on') }}"), - ], - } - ) - == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"} - ) + assert condition.async_extract_devices( + { + "condition": "and", + "conditions": [ + {"condition": "device", "device_id": "abcd", "domain": "light"}, + {"condition": "device", "device_id": "qwer", "domain": "switch"}, + { + "condition": "state", + "entity_id": "sensor.not_a_device", + "state": "100", + }, + { + "condition": "not", + "conditions": [ + { + "condition": "device", + "device_id": "abcd_not", + "domain": "light", + }, + { + "condition": "device", + "device_id": "qwer_not", + "domain": "switch", + }, + ], + }, + { + "condition": "or", + "conditions": [ + { + "condition": "device", + "device_id": "abcd_or", + "domain": "light", + }, + { + "condition": "device", + "device_id": "qwer_or", + "domain": "switch", + }, + ], + }, + Template("{{ is_state('light.example', 'on') }}"), + ], + } + ) == {"abcd", "qwer", "abcd_not", "qwer_not", "abcd_or", "qwer_or"} async def test_condition_template_error(hass): diff --git a/tests/test_config.py b/tests/test_config.py index 41e9bc500380..93dd1b87b444 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1050,23 +1050,20 @@ async def test_component_config_exceptions(hass, caplog): # component.PLATFORM_SCHEMA caplog.clear() - assert ( - await config_util.async_process_component_config( - hass, - {"test_domain": {"platform": "test_platform"}}, - integration=Mock( - domain="test_domain", - get_platform=Mock(return_value=None), - get_component=Mock( - return_value=Mock( - spec=["PLATFORM_SCHEMA_BASE"], - PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")), - ) - ), + assert await config_util.async_process_component_config( + hass, + {"test_domain": {"platform": "test_platform"}}, + integration=Mock( + domain="test_domain", + get_platform=Mock(return_value=None), + get_component=Mock( + return_value=Mock( + spec=["PLATFORM_SCHEMA_BASE"], + PLATFORM_SCHEMA_BASE=Mock(side_effect=ValueError("broken")), + ) ), - ) - == {"test_domain": []} - ) + ), + ) == {"test_domain": []} assert "ValueError: broken" in caplog.text assert ( "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 ( - await config_util.async_process_component_config( - hass, - {"test_domain": {"platform": "test_platform"}}, - integration=Mock( - domain="test_domain", - get_platform=Mock(return_value=None), - get_component=Mock( - return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"]) - ), - ), - ) - == {"test_domain": []} - ) + assert await config_util.async_process_component_config( + hass, + {"test_domain": {"platform": "test_platform"}}, + integration=Mock( + domain="test_domain", + get_platform=Mock(return_value=None), + get_component=Mock(return_value=Mock(spec=["PLATFORM_SCHEMA_BASE"])), + ), + ) == {"test_domain": []} assert "ValueError: broken" in caplog.text assert ( "Unknown error validating config for test_platform platform for test_domain component with PLATFORM_SCHEMA" diff --git a/tests/test_util/aiohttp.py b/tests/test_util/aiohttp.py index 31a8a5c71e32..6868ff1f71db 100644 --- a/tests/test_util/aiohttp.py +++ b/tests/test_util/aiohttp.py @@ -21,7 +21,7 @@ RETYPE = type(re.compile("")) def mock_stream(data): """Mock a stream with data.""" protocol = mock.Mock(_reading_paused=False) - stream = StreamReader(protocol, limit=2 ** 16) + stream = StreamReader(protocol, limit=2**16) stream.feed_data(data) stream.feed_eof() return stream diff --git a/tests/util/test_color.py b/tests/util/test_color.py index 0b1b8f7d17f4..e9ab935f6ab3 100644 --- a/tests/util/test_color.py +++ b/tests/util/test_color.py @@ -461,20 +461,17 @@ def test_rgbww_to_color_temperature(): Temperature values must be in mireds Home Assistant uses rgbcw for rgbww """ - assert ( - color_util.rgbww_to_color_temperature( - ( - 0, - 0, - 0, - 255, - 0, - ), - 153, - 500, - ) - == (153, 255) - ) + assert color_util.rgbww_to_color_temperature( + ( + 0, + 0, + 0, + 255, + 0, + ), + 153, + 500, + ) == (153, 255) assert color_util.rgbww_to_color_temperature((0, 0, 0, 128, 0), 153, 500) == ( 153, 128, @@ -507,15 +504,12 @@ def test_white_levels_to_color_temperature(): Temperature values must be in mireds Home Assistant uses rgbcw for rgbww """ - assert ( - color_util.while_levels_to_color_temperature( - 255, - 0, - 153, - 500, - ) - == (153, 255) - ) + assert color_util.while_levels_to_color_temperature( + 255, + 0, + 153, + 500, + ) == (153, 255) assert color_util.while_levels_to_color_temperature(128, 0, 153, 500) == ( 153, 128, diff --git a/tests/util/test_json.py b/tests/util/test_json.py index d88518687198..af7f43eae4d1 100644 --- a/tests/util/test_json.py +++ b/tests/util/test_json.py @@ -143,21 +143,15 @@ def test_find_unserializable_data(): bad_data = object() - assert ( - find_paths_unserializable_data( - [State("mock_domain.mock_entity", "on", {"bad": bad_data})], - dump=partial(dumps, cls=MockJSONEncoder), - ) - == {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data} - ) + assert find_paths_unserializable_data( + [State("mock_domain.mock_entity", "on", {"bad": bad_data})], + dump=partial(dumps, cls=MockJSONEncoder), + ) == {"$[0](State: mock_domain.mock_entity).attributes.bad": bad_data} - assert ( - find_paths_unserializable_data( - [Event("bad_event", {"bad_attribute": bad_data})], - dump=partial(dumps, cls=MockJSONEncoder), - ) - == {"$[0](Event: bad_event).data.bad_attribute": bad_data} - ) + assert find_paths_unserializable_data( + [Event("bad_event", {"bad_attribute": bad_data})], + dump=partial(dumps, cls=MockJSONEncoder), + ) == {"$[0](Event: bad_event).data.bad_attribute": bad_data} class BadData: def __init__(self): @@ -166,10 +160,7 @@ def test_find_unserializable_data(): def as_dict(self): return {"bla": self.bla} - assert ( - find_paths_unserializable_data( - BadData(), - dump=partial(dumps, cls=MockJSONEncoder), - ) - == {"$(BadData).bla": bad_data} - ) + assert find_paths_unserializable_data( + BadData(), + dump=partial(dumps, cls=MockJSONEncoder), + ) == {"$(BadData).bla": bad_data} diff --git a/tests/util/yaml/test_input.py b/tests/util/yaml/test_input.py index 1c13d1b36847..fe118c79dbd0 100644 --- a/tests/util/yaml/test_input.py +++ b/tests/util/yaml/test_input.py @@ -25,10 +25,7 @@ def test_substitute(): with pytest.raises(UndefinedSubstitution): substitute(Input("hello"), {}) - assert ( - substitute( - {"info": [1, Input("hello"), 2, Input("world")]}, - {"hello": 5, "world": 10}, - ) - == {"info": [1, 5, 2, 10]} - ) + assert substitute( + {"info": [1, Input("hello"), 2, Input("world")]}, + {"hello": 5, "world": 10}, + ) == {"info": [1, 5, 2, 10]}