Use assignment expressions 29 (#58713)

This commit is contained in:
Marc Mueller 2021-10-30 16:31:43 +02:00 committed by GitHub
parent 887d04be60
commit b1d49b3b66
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 27 additions and 62 deletions

View File

@ -111,8 +111,7 @@ class AcerSwitch(SwitchEntity):
"""Write msg, obtain answer and format output."""
# answers are formatted as ***\answer\r***
awns = self._write_read(msg)
match = re.search(r"\r(.+)\r", awns)
if match:
if match := re.search(r"\r(.+)\r", awns):
return match.group(1)
return STATE_UNKNOWN

View File

@ -59,9 +59,7 @@ def _get_github_import_url(url: str) -> str:
if url.startswith("https://raw.githubusercontent.com/"):
return url
match = GITHUB_FILE_PATTERN.match(url)
if match is None:
if (match := GITHUB_FILE_PATTERN.match(url)) is None:
raise UnsupportedUrl("Not a GitHub file url")
repo, path = match.groups()
@ -74,8 +72,7 @@ def _get_community_post_import_url(url: str) -> str:
Async friendly.
"""
match = COMMUNITY_TOPIC_PATTERN.match(url)
if match is None:
if (match := COMMUNITY_TOPIC_PATTERN.match(url)) is None:
raise UnsupportedUrl("Not a topic url")
_topic, post = match.groups()

View File

@ -118,9 +118,7 @@ class DefaultAgent(AbstractConversationAgent):
for intent_type, matchers in intents.items():
for matcher in matchers:
match = matcher.match(text)
if not match:
if not (match := matcher.match(text)):
continue
return await intent.async_handle(

View File

@ -130,16 +130,14 @@ async def ws_get_statistics_during_period(
start_time_str = msg["start_time"]
end_time_str = msg.get("end_time")
start_time = dt_util.parse_datetime(start_time_str)
if start_time:
if start_time := dt_util.parse_datetime(start_time_str):
start_time = dt_util.as_utc(start_time)
else:
connection.send_error(msg["id"], "invalid_start_time", "Invalid start_time")
return
if end_time_str:
end_time = dt_util.parse_datetime(end_time_str)
if end_time:
if end_time := dt_util.parse_datetime(end_time_str):
end_time = dt_util.as_utc(end_time)
else:
connection.send_error(msg["id"], "invalid_end_time", "Invalid end_time")
@ -194,11 +192,8 @@ class HistoryPeriodView(HomeAssistantView):
) -> web.Response:
"""Return history over a period of time."""
datetime_ = None
if datetime:
datetime_ = dt_util.parse_datetime(datetime)
if datetime_ is None:
return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST)
if datetime and (datetime_ := dt_util.parse_datetime(datetime)) is None:
return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST)
now = dt_util.utcnow()
@ -212,8 +207,7 @@ class HistoryPeriodView(HomeAssistantView):
return self.json([])
if end_time_str := request.query.get("end_time"):
end_time = dt_util.parse_datetime(end_time_str)
if end_time:
if end_time := dt_util.parse_datetime(end_time_str):
end_time = dt_util.as_utc(end_time)
else:
return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST)

View File

@ -87,19 +87,16 @@ def valid_initial(conf):
return conf
if conf[CONF_HAS_DATE] and conf[CONF_HAS_TIME]:
parsed_value = dt_util.parse_datetime(initial)
if parsed_value is not None:
if dt_util.parse_datetime(initial) is not None:
return conf
raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a datetime")
if conf[CONF_HAS_DATE]:
parsed_value = dt_util.parse_date(initial)
if parsed_value is not None:
if dt_util.parse_date(initial) is not None:
return conf
raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a date")
parsed_value = dt_util.parse_time(initial)
if parsed_value is not None:
if dt_util.parse_time(initial) is not None:
return conf
raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a time")
@ -282,15 +279,13 @@ class InputDatetime(RestoreEntity):
current_datetime = date_time
elif self.has_date:
date = dt_util.parse_date(old_state.state)
if date is None:
if (date := dt_util.parse_date(old_state.state)) is None:
current_datetime = dt_util.parse_datetime(default_value)
else:
current_datetime = py_datetime.datetime.combine(date, DEFAULT_TIME)
else:
time = dt_util.parse_time(old_state.state)
if time is None:
if (time := dt_util.parse_time(old_state.state)) is None:
current_datetime = dt_util.parse_datetime(default_value)
else:
current_datetime = py_datetime.datetime.combine(

View File

@ -385,8 +385,7 @@ def is_address(value: str) -> tuple[AddressType, str]:
myhome.0.g11
myhome.s0.g11
"""
matcher = PATTERN_ADDRESS.match(value)
if matcher:
if matcher := PATTERN_ADDRESS.match(value):
is_group = matcher.group("type") == "g"
addr = (int(matcher.group("seg_id")), int(matcher.group("id")), is_group)
conn_id = matcher.group("conn_id")

View File

@ -99,9 +99,7 @@ class LitterRobotControlEntity(LitterRobotEntity):
@staticmethod
def parse_time_at_default_timezone(time_str: str) -> time | None:
"""Parse a time string and add default timezone."""
parsed_time = dt_util.parse_time(time_str)
if parsed_time is None:
if (parsed_time := dt_util.parse_time(time_str)) is None:
return None
return (

View File

@ -22,8 +22,7 @@ def normalize_metadata(metadata: dict) -> dict:
"""Normalize object metadata by stripping the prefix."""
new_metadata = {}
for meta_key, meta_value in metadata.items():
match = _METADATA_RE.match(meta_key)
if not match:
if not (match := _METADATA_RE.match(meta_key)):
continue
new_metadata[match.group(1).lower()] = meta_value

View File

@ -97,9 +97,8 @@ async def async_start( # noqa: C901
payload = msg.payload
topic = msg.topic
topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1)
match = TOPIC_MATCHER.match(topic_trimmed)
if not match:
if not (match := TOPIC_MATCHER.match(topic_trimmed)):
if topic_trimmed.endswith("config"):
_LOGGER.warning(
"Received message on illegal discovery topic '%s'", topic

View File

@ -157,8 +157,7 @@ class OpenUvSensor(OpenUvEntity, SensorEntity):
self._attr_native_value = UV_LEVEL_LOW
elif self.entity_description.key == TYPE_MAX_UV_INDEX:
self._attr_native_value = data["uv_max"]
uv_max_time = parse_datetime(data["uv_max_time"])
if uv_max_time:
if uv_max_time := parse_datetime(data["uv_max_time"]):
self._attr_extra_state_attributes.update(
{ATTR_MAX_UV_TIME: as_local(uv_max_time)}
)

View File

@ -96,9 +96,7 @@ def entities_in_script(hass: HomeAssistant, entity_id: str) -> list[str]:
component = hass.data[DOMAIN]
script_entity = component.get_entity(entity_id)
if script_entity is None:
if (script_entity := component.get_entity(entity_id)) is None:
return []
return list(script_entity.script.referenced_entities)
@ -127,9 +125,7 @@ def devices_in_script(hass: HomeAssistant, entity_id: str) -> list[str]:
component = hass.data[DOMAIN]
script_entity = component.get_entity(entity_id)
if script_entity is None:
if (script_entity := component.get_entity(entity_id)) is None:
return []
return list(script_entity.script.referenced_devices)
@ -158,9 +154,7 @@ def areas_in_script(hass: HomeAssistant, entity_id: str) -> list[str]:
component = hass.data[DOMAIN]
script_entity = component.get_entity(entity_id)
if script_entity is None:
if (script_entity := component.get_entity(entity_id)) is None:
return []
return list(script_entity.script.referenced_areas)

View File

@ -462,8 +462,7 @@ class SpeechManager:
This method is a coroutine.
"""
record = _RE_VOICE_FILE.match(filename.lower())
if not record:
if not (record := _RE_VOICE_FILE.match(filename.lower())):
raise HomeAssistantError("Wrong tts file format!")
key = KEY_PATTERN.format(
@ -571,8 +570,7 @@ def _get_cache_files(cache_dir):
folder_data = os.listdir(cache_dir)
for file_data in folder_data:
record = _RE_VOICE_FILE.match(file_data)
if record:
if record := _RE_VOICE_FILE.match(file_data):
key = KEY_PATTERN.format(
record.group(1), record.group(2), record.group(3), record.group(4)
)

View File

@ -161,8 +161,7 @@ class XiaomiMiioFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.mac = discovery_info.get("properties", {}).get("mac")
if self.mac is None:
poch = discovery_info.get("properties", {}).get("poch", "")
result = search(r"mac=\w+", poch)
if result is not None:
if (result := search(r"mac=\w+", poch)) is not None:
self.mac = result.group(0).split("=")[1]
if not name or not self.host or not self.mac:

View File

@ -49,9 +49,7 @@ async def async_update_entity(hass: HomeAssistant, entity_id: str) -> None:
)
return
entity_obj = entity_comp.get_entity(entity_id)
if entity_obj is None:
if (entity_obj := entity_comp.get_entity(entity_id)) is None:
logging.getLogger(__name__).warning(
"Forced update failed. Entity %s not found.", entity_id
)

View File

@ -168,8 +168,7 @@ def _fuzzymatch(name: str, items: Iterable[T], key: Callable[[T], str]) -> T | N
pattern = ".*?".join(name)
regex = re.compile(pattern, re.IGNORECASE)
for idx, item in enumerate(items):
match = regex.search(key(item))
if match:
if match := regex.search(key(item)):
# Add key length so we prefer shorter keys with the same group and start.
# Add index so we pick first match in case same group, start, and key length.
matches.append(