Use assignment expressions 27 (#58188)

pull/58181/head
Marc Mueller 2021-10-22 11:29:21 +02:00 committed by GitHub
parent 83e45300c2
commit be201e3ebe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 29 additions and 59 deletions

View File

@ -48,9 +48,7 @@ async def _async_reproduce_state(
reproduce_options: dict[str, Any] | None = None,
) -> None:
"""Reproduce a single state."""
cur_state = hass.states.get(state.entity_id)
if cur_state is None:
if (cur_state := hass.states.get(state.entity_id)) is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return

View File

@ -28,9 +28,8 @@ async def async_setup_entry(
) -> None:
"""Set up a config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id]
api_version = config_entry.data[CONF_API_VERSION]
if api_version == 3:
if (api_version := config_entry.data[CONF_API_VERSION]) == 3:
api_class = ClimaCellV3SensorEntity
sensor_types = CC_V3_SENSOR_TYPES
else:

View File

@ -51,8 +51,7 @@ CONFIG_SCHEMA = vol.Schema(
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the emulated_kasa component."""
conf = config.get(DOMAIN)
if not conf:
if not (conf := config.get(DOMAIN)):
return True
entity_configs = conf[CONF_ENTITIES]
@ -83,13 +82,11 @@ async def validate_configs(hass, entity_configs):
"""Validate that entities exist and ensure templates are ready to use."""
entity_registry = await hass.helpers.entity_registry.async_get_registry()
for entity_id, entity_config in entity_configs.items():
state = hass.states.get(entity_id)
if state is None:
if (state := hass.states.get(entity_id)) is None:
_LOGGER.debug("Entity not found: %s", entity_id)
continue
entity = entity_registry.async_get(entity_id)
if entity:
if entity := entity_registry.async_get(entity_id):
entity_config[CONF_UNIQUE_ID] = get_system_unique_id(entity)
else:
entity_config[CONF_UNIQUE_ID] = entity_id
@ -122,8 +119,7 @@ def get_system_unique_id(entity: RegistryEntry):
def get_plug_devices(hass, entity_configs):
"""Produce list of plug devices from config entities."""
for entity_id, entity_config in entity_configs.items():
state = hass.states.get(entity_id)
if state is None:
if (state := hass.states.get(entity_id)) is None:
continue
name = entity_config.get(CONF_NAME, state.name)

View File

@ -230,9 +230,8 @@ class EvoZone(EvoChild, EvoClimateEntity):
async def async_set_temperature(self, **kwargs) -> None:
"""Set a new target temperature."""
temperature = kwargs["temperature"]
until = kwargs.get("until")
if until is None:
if (until := kwargs.get("until")) is None:
if self._evo_device.setpointStatus["setpointMode"] == EVO_FOLLOW:
await self._update_schedule()
until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", ""))

View File

@ -33,9 +33,8 @@ def with_store(orig_func: Callable) -> Callable:
"""Provide user specific data and store to function."""
stores, data = hass.data[DATA_STORAGE]
user_id = connection.user.id
store = stores.get(user_id)
if store is None:
if (store := stores.get(user_id)) is None:
store = stores[user_id] = hass.helpers.storage.Store(
STORAGE_VERSION_USER_DATA, f"frontend.user_data_{connection.user.id}"
)

View File

@ -233,8 +233,7 @@ def setup(hass, config):
if DATA_INDEX not in hass.data:
hass.data[DATA_INDEX] = {}
conf = config.get(DOMAIN, {})
if not conf:
if not (conf := config.get(DOMAIN, {})):
# component is set up by tts platform
return True

View File

@ -133,8 +133,7 @@ class HMThermostat(HMDevice, ClimateEntity):
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
return None
self._hmdevice.writeNodeData(self._state, float(temperature))

View File

@ -161,8 +161,7 @@ class ImageProcessingFaceEntity(ImageProcessingEntity):
if ATTR_CONFIDENCE not in face:
continue
f_co = face[ATTR_CONFIDENCE]
if f_co > confidence:
if (f_co := face[ATTR_CONFIDENCE]) > confidence:
confidence = f_co
for attr in (ATTR_NAME, ATTR_MOTION):
if attr in face:

View File

@ -15,8 +15,7 @@ PLATFORMS = [SENSOR_DOMAIN]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up IPP from a config entry."""
hass.data.setdefault(DOMAIN, {})
coordinator = hass.data[DOMAIN].get(entry.entry_id)
if not coordinator:
if not (coordinator := hass.data[DOMAIN].get(entry.entry_id)):
# Create IPP instance for this entry
coordinator = IPPDataUpdateCoordinator(
hass,

View File

@ -140,9 +140,7 @@ class MpdDevice(MediaPlayerEntity):
self._status = await self._client.status()
self._currentsong = await self._client.currentsong()
position = self._status.get("elapsed")
if position is None:
if (position := self._status.get("elapsed")) is None:
position = self._status.get("time")
if isinstance(position, str) and ":" in position:
@ -257,16 +255,14 @@ class MpdDevice(MediaPlayerEntity):
@property
def media_image_hash(self):
"""Hash value for media image."""
file = self._currentsong.get("file")
if file:
if file := self._currentsong.get("file"):
return hashlib.sha256(file.encode("utf-8")).hexdigest()[:16]
return None
async def async_get_media_image(self):
"""Fetch media image of current playing track."""
file = self._currentsong.get("file")
if not file:
if not (file := self._currentsong.get("file")):
return None, None
# not all MPD implementations and versions support the `albumart` and `fetchpicture` commands

View File

@ -68,9 +68,8 @@ class PushoverNotificationService(BaseNotificationService):
sound = data.get(ATTR_SOUND)
html = 1 if data.get(ATTR_HTML, False) else 0
image = data.get(ATTR_ATTACHMENT)
# Check for attachment
if image is not None:
if (image := data.get(ATTR_ATTACHMENT)) is not None:
# Only allow attachments from whitelisted paths, check valid path
if self._hass.config.is_allowed_path(data[ATTR_ATTACHMENT]):
# try to open it as a normal file.

View File

@ -118,8 +118,7 @@ class I2CHatsManager(threading.Thread):
def register_board(self, board, address):
"""Register I2C-HAT."""
with self._lock:
i2c_hat = self._i2c_hats.get(address)
if i2c_hat is None:
if (i2c_hat := self._i2c_hats.get(address)) is None:
# This is a Pi module and can't be installed in CI without
# breaking the build.
# pylint: disable=import-outside-toplevel,import-error

View File

@ -206,8 +206,7 @@ async def async_setup(hass, config):
discovery.async_listen(hass, SERVICE_SABNZBD, sabnzbd_discovered)
conf = config.get(DOMAIN)
if conf is not None:
if (conf := config.get(DOMAIN)) is not None:
use_ssl = conf[CONF_SSL]
name = conf.get(CONF_NAME)
api_key = conf.get(CONF_API_KEY)

View File

@ -66,8 +66,8 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
value_template.hass = hass
if username and password:

View File

@ -81,8 +81,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
rtscts = config.get(CONF_RTSCTS)
dsrdtr = config.get(CONF_DSRDTR)
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
value_template.hass = hass
sensor = SerialSensor(

View File

@ -24,8 +24,7 @@ PLATFORMS = ["media_player"]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up songpal environment."""
conf = config.get(DOMAIN)
if conf is None:
if (conf := config.get(DOMAIN)) is None:
return True
for config_entry in conf:
hass.async_create_task(

View File

@ -190,8 +190,7 @@ class SuplaChannel(CoordinatorEntity):
"""Return True if entity is available."""
if self.channel_data is None:
return False
state = self.channel_data.get("state")
if state is None:
if (state := self.channel_data.get("state")) is None:
return False
return state.get("connected")

View File

@ -59,8 +59,7 @@ class SuplaCover(SuplaChannel, CoverEntity):
@property
def current_cover_position(self):
"""Return current position of cover. 0 is closed, 100 is open."""
state = self.channel_data.get("state")
if state:
if state := self.channel_data.get("state"):
return 100 - state["shut"]
return None

View File

@ -49,7 +49,6 @@ class SuplaSwitch(SuplaChannel, SwitchEntity):
@property
def is_on(self):
"""Return true if switch is on."""
state = self.channel_data.get("state")
if state:
if state := self.channel_data.get("state"):
return state["on"]
return False

View File

@ -177,9 +177,7 @@ class WatsonIOTThread(threading.Thread):
events = []
try:
item = self.queue.get()
if item is None:
if (item := self.queue.get()) is None:
self.shutdown = True
else:
event_json = self.event_to_json(item[1])

View File

@ -156,8 +156,7 @@ class AirConEntity(ClimateEntity):
await self._aircon.set_power_on(False)
return
mode = HVAC_MODE_TO_AIRCON_MODE.get(hvac_mode)
if not mode:
if not (mode := HVAC_MODE_TO_AIRCON_MODE.get(hvac_mode)):
raise ValueError(f"Invalid hvac mode {hvac_mode}")
await self._aircon.set_mode(mode)
@ -172,8 +171,7 @@ class AirConEntity(ClimateEntity):
async def async_set_fan_mode(self, fan_mode):
"""Set fan mode."""
fanspeed = FAN_MODE_TO_AIRCON_FANSPEED.get(fan_mode)
if not fanspeed:
if not (fanspeed := FAN_MODE_TO_AIRCON_FANSPEED.get(fan_mode)):
raise ValueError(f"Invalid fan mode {fan_mode}")
await self._aircon.set_fanspeed(fanspeed)

View File

@ -199,8 +199,7 @@ class WirelessTagBaseSensor(Entity):
return
updated_tags = self._api.load_tags()
updated_tag = updated_tags[self._uuid]
if updated_tag is None:
if (updated_tag := updated_tags[self._uuid]) is None:
_LOGGER.error('Unable to update tag: "%s"', self.name)
return