Use assignment expressions 36 (#58825)

This commit is contained in:
Marc Mueller 2021-10-31 18:35:27 +01:00 committed by GitHub
parent 3f1b4906bf
commit 1ce889be60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 28 additions and 60 deletions

View File

@ -226,9 +226,7 @@ class EditIdBasedConfigView(BaseEditConfigView):
def _write_value(self, hass, data, config_key, new_value): def _write_value(self, hass, data, config_key, new_value):
"""Set value.""" """Set value."""
value = self._get_value(hass, data, config_key) if (value := self._get_value(hass, data, config_key)) is None:
if value is None:
value = {CONF_ID: config_key} value = {CONF_ID: config_key}
data.append(value) data.append(value)

View File

@ -48,9 +48,7 @@ async def websocket_delete(hass, connection, msg):
) )
return return
user = await hass.auth.async_get_user(msg["user_id"]) if not (user := await hass.auth.async_get_user(msg["user_id"])):
if not user:
connection.send_message( connection.send_message(
websocket_api.error_message(msg["id"], "not_found", "User not found") websocket_api.error_message(msg["id"], "not_found", "User not found")
) )
@ -92,9 +90,7 @@ async def websocket_create(hass, connection, msg):
) )
async def websocket_update(hass, connection, msg): async def websocket_update(hass, connection, msg):
"""Update a user.""" """Update a user."""
user = await hass.auth.async_get_user(msg.pop("user_id")) if not (user := await hass.auth.async_get_user(msg.pop("user_id"))):
if not user:
connection.send_message( connection.send_message(
websocket_api.error_message( websocket_api.error_message(
msg["id"], websocket_api.const.ERR_NOT_FOUND, "User not found" msg["id"], websocket_api.const.ERR_NOT_FOUND, "User not found"

View File

@ -31,9 +31,8 @@ async def async_setup(hass):
async def websocket_create(hass, connection, msg): async def websocket_create(hass, connection, msg):
"""Create credentials and attach to a user.""" """Create credentials and attach to a user."""
provider = auth_ha.async_get_provider(hass) provider = auth_ha.async_get_provider(hass)
user = await hass.auth.async_get_user(msg["user_id"])
if user is None: if (user := await hass.auth.async_get_user(msg["user_id"])) is None:
connection.send_error(msg["id"], "not_found", "User not found") connection.send_error(msg["id"], "not_found", "User not found")
return return
@ -149,9 +148,7 @@ async def websocket_admin_change_password(hass, connection, msg):
if not connection.user.is_owner: if not connection.user.is_owner:
raise Unauthorized(context=connection.context(msg)) raise Unauthorized(context=connection.context(msg))
user = await hass.auth.async_get_user(msg["user_id"]) if (user := await hass.auth.async_get_user(msg["user_id"])) is None:
if user is None:
connection.send_error(msg["id"], "user_not_found", "User not found") connection.send_error(msg["id"], "user_not_found", "User not found")
return return

View File

@ -249,8 +249,7 @@ def get_entry(
msg_id: int, msg_id: int,
) -> config_entries.ConfigEntry | None: ) -> config_entries.ConfigEntry | None:
"""Get entry, send error message if it doesn't exist.""" """Get entry, send error message if it doesn't exist."""
entry = hass.config_entries.async_get_entry(entry_id) if (entry := hass.config_entries.async_get_entry(entry_id)) is None:
if entry is None:
send_entry_not_found(connection, msg_id) send_entry_not_found(connection, msg_id)
return entry return entry

View File

@ -67,8 +67,7 @@ class DdWrtDeviceScanner(DeviceScanner):
# Test the router is accessible # Test the router is accessible
url = f"{self.protocol}://{self.host}/Status_Wireless.live.asp" url = f"{self.protocol}://{self.host}/Status_Wireless.live.asp"
data = self.get_ddwrt_data(url) if not self.get_ddwrt_data(url):
if not data:
raise ConnectionError("Cannot connect to DD-Wrt router") raise ConnectionError("Cannot connect to DD-Wrt router")
def scan_devices(self): def scan_devices(self):
@ -82,9 +81,8 @@ class DdWrtDeviceScanner(DeviceScanner):
# If not initialised and not already scanned and not found. # If not initialised and not already scanned and not found.
if device not in self.mac2name: if device not in self.mac2name:
url = f"{self.protocol}://{self.host}/Status_Lan.live.asp" url = f"{self.protocol}://{self.host}/Status_Lan.live.asp"
data = self.get_ddwrt_data(url)
if not data: if not (data := self.get_ddwrt_data(url)):
return None return None
if not (dhcp_leases := data.get("dhcp_leases")): if not (dhcp_leases := data.get("dhcp_leases")):
@ -115,9 +113,8 @@ class DdWrtDeviceScanner(DeviceScanner):
endpoint = "Wireless" if self.wireless_only else "Lan" endpoint = "Wireless" if self.wireless_only else "Lan"
url = f"{self.protocol}://{self.host}/Status_{endpoint}.live.asp" url = f"{self.protocol}://{self.host}/Status_{endpoint}.live.asp"
data = self.get_ddwrt_data(url)
if not data: if not (data := self.get_ddwrt_data(url)):
return False return False
self.last_results = [] self.last_results = []

View File

@ -43,8 +43,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
dev = [] dev = []
for droplet in droplets: for droplet in droplets:
droplet_id = digital.get_droplet_id(droplet) if (droplet_id := digital.get_droplet_id(droplet)) is None:
if droplet_id is None:
_LOGGER.error("Droplet %s is not available", droplet) _LOGGER.error("Droplet %s is not available", droplet)
return False return False
dev.append(DigitalOceanBinarySensor(digital, droplet_id)) dev.append(DigitalOceanBinarySensor(digital, droplet_id))

View File

@ -40,8 +40,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
dev = [] dev = []
for droplet in droplets: for droplet in droplets:
droplet_id = digital.get_droplet_id(droplet) if (droplet_id := digital.get_droplet_id(droplet)) is None:
if droplet_id is None:
_LOGGER.error("Droplet %s is not available", droplet) _LOGGER.error("Droplet %s is not available", droplet)
return False return False
dev.append(DigitalOceanSwitch(digital, droplet_id)) dev.append(DigitalOceanSwitch(digital, droplet_id))

View File

@ -100,8 +100,7 @@ class EpsonProjectorMediaPlayer(MediaPlayerEntity):
_LOGGER.debug("Setting unique_id for projector") _LOGGER.debug("Setting unique_id for projector")
if self._unique_id: if self._unique_id:
return False return False
uid = await self._projector.get_serial_number() if uid := await self._projector.get_serial_number():
if uid:
self.hass.config_entries.async_update_entry(self._entry, unique_id=uid) self.hass.config_entries.async_update_entry(self._entry, unique_id=uid)
registry = async_get_entity_registry(self.hass) registry = async_get_entity_registry(self.hass)
old_entity_id = registry.async_get_entity_id( old_entity_id = registry.async_get_entity_id(

View File

@ -211,8 +211,7 @@ class GPMDP(MediaPlayerEntity):
"""Send ws messages to GPMDP and verify request id in response.""" """Send ws messages to GPMDP and verify request id in response."""
try: try:
websocket = self.get_ws() if (websocket := self.get_ws()) is None:
if websocket is None:
self._status = STATE_OFF self._status = STATE_OFF
return return
self._request_id += 1 self._request_id += 1
@ -342,8 +341,7 @@ class GPMDP(MediaPlayerEntity):
def media_seek(self, position): def media_seek(self, position):
"""Send media_seek command to media player.""" """Send media_seek command to media player."""
websocket = self.get_ws() if (websocket := self.get_ws()) is None:
if websocket is None:
return return
websocket.send( websocket.send(
json.dumps( json.dumps(
@ -358,24 +356,21 @@ class GPMDP(MediaPlayerEntity):
def volume_up(self): def volume_up(self):
"""Send volume_up command to media player.""" """Send volume_up command to media player."""
websocket = self.get_ws() if (websocket := self.get_ws()) is None:
if websocket is None:
return return
websocket.send('{"namespace": "volume", "method": "increaseVolume"}') websocket.send('{"namespace": "volume", "method": "increaseVolume"}')
self.schedule_update_ha_state() self.schedule_update_ha_state()
def volume_down(self): def volume_down(self):
"""Send volume_down command to media player.""" """Send volume_down command to media player."""
websocket = self.get_ws() if (websocket := self.get_ws()) is None:
if websocket is None:
return return
websocket.send('{"namespace": "volume", "method": "decreaseVolume"}') websocket.send('{"namespace": "volume", "method": "decreaseVolume"}')
self.schedule_update_ha_state() self.schedule_update_ha_state()
def set_volume_level(self, volume): def set_volume_level(self, volume):
"""Set volume on media player, range(0..1).""" """Set volume on media player, range(0..1)."""
websocket = self.get_ws() if (websocket := self.get_ws()) is None:
if websocket is None:
return return
websocket.send( websocket.send(
json.dumps( json.dumps(

View File

@ -120,8 +120,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
_LOGGER.error("Error connecting to the %s server", device_type) _LOGGER.error("Error connecting to the %s server", device_type)
raise PlatformNotReady from ex raise PlatformNotReady from ex
ih_devices = controller.get_devices() if ih_devices := controller.get_devices():
if ih_devices:
async_add_entities( async_add_entities(
[ [
IntesisAC(ih_device_id, device, controller) IntesisAC(ih_device_id, device, controller)
@ -194,8 +193,7 @@ class IntesisAC(ClimateEntity):
self._support |= SUPPORT_PRESET_MODE self._support |= SUPPORT_PRESET_MODE
# Setup HVAC modes # Setup HVAC modes
modes = controller.get_mode_list(ih_device_id) if modes := controller.get_mode_list(ih_device_id):
if modes:
mode_list = [MAP_IH_TO_HVAC_MODE[mode] for mode in modes] mode_list = [MAP_IH_TO_HVAC_MODE[mode] for mode in modes]
self._hvac_mode_list.extend(mode_list) self._hvac_mode_list.extend(mode_list)
self._hvac_mode_list.append(HVAC_MODE_OFF) self._hvac_mode_list.append(HVAC_MODE_OFF)

View File

@ -91,8 +91,7 @@ class LcnFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_abort(reason="connection_timeout") return self.async_abort(reason="connection_timeout")
# check if we already have a host with the same address configured # check if we already have a host with the same address configured
entry = get_config_entry(self.hass, data) if entry := get_config_entry(self.hass, data):
if entry:
entry.source = config_entries.SOURCE_IMPORT entry.source = config_entries.SOURCE_IMPORT
# Cleanup entity and device registry, if we imported from configuration.yaml to # Cleanup entity and device registry, if we imported from configuration.yaml to

View File

@ -235,8 +235,7 @@ async def async_get_triggers(
"""List device triggers for lutron caseta devices.""" """List device triggers for lutron caseta devices."""
triggers = [] triggers = []
device = get_button_device_by_dr_id(hass, device_id) if not (device := get_button_device_by_dr_id(hass, device_id)):
if not device:
raise InvalidDeviceAutomationConfig(f"Device not found: {device_id}") raise InvalidDeviceAutomationConfig(f"Device not found: {device_id}")
valid_buttons = DEVICE_TYPE_SUBTYPE_MAP.get(device["type"], []) valid_buttons = DEVICE_TYPE_SUBTYPE_MAP.get(device["type"], [])

View File

@ -89,8 +89,7 @@ class MeteoAlertBinarySensor(BinarySensorEntity):
self._attributes = {} self._attributes = {}
self._state = False self._state = False
alert = self._api.get_alert() if alert := self._api.get_alert():
if alert:
expiration_date = dt_util.parse_datetime(alert["expires"]) expiration_date = dt_util.parse_datetime(alert["expires"])
now = dt_util.utcnow() now = dt_util.utcnow()

View File

@ -197,8 +197,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
known_players.append(entity) known_players.append(entity)
async_add_entities([entity]) async_add_entities([entity])
players = await lms.async_get_players() if players := await lms.async_get_players():
if players:
for player in players: for player in players:
hass.async_create_task(_discovered_player(player)) hass.async_create_task(_discovered_player(player))

View File

@ -125,8 +125,7 @@ async def refresh_subaru_data(config_entry, vehicle_info, controller):
await controller.fetch(vin, force=True) await controller.fetch(vin, force=True)
# Update our local data that will go to entity states # Update our local data that will go to entity states
received_data = await controller.get_data(vin) if received_data := await controller.get_data(vin):
if received_data:
data[vin] = received_data data[vin] = received_data
return data return data

View File

@ -65,8 +65,7 @@ class SwisscomDeviceScanner(DeviceScanner):
return False return False
_LOGGER.info("Loading data from Swisscom Internet Box") _LOGGER.info("Loading data from Swisscom Internet Box")
data = self.get_swisscom_data() if not (data := self.get_swisscom_data()):
if not data:
return False return False
active_clients = [client for client in data.values() if client["status"]] active_clients = [client for client in data.values() if client["status"]]

View File

@ -19,8 +19,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
filter_urllib3_logging() filter_urllib3_logging()
cameras = [] cameras = []
for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
monitors = zm_client.get_monitors() if not (monitors := zm_client.get_monitors()):
if not monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder host: %s") _LOGGER.warning("Could not fetch monitors from ZoneMinder host: %s")
return return

View File

@ -66,8 +66,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
sensors = [] sensors = []
for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
monitors = zm_client.get_monitors() if not (monitors := zm_client.get_monitors()):
if not monitors:
_LOGGER.warning("Could not fetch any monitors from ZoneMinder") _LOGGER.warning("Could not fetch any monitors from ZoneMinder")
for monitor in monitors: for monitor in monitors:

View File

@ -28,8 +28,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
switches = [] switches = []
for zm_client in hass.data[ZONEMINDER_DOMAIN].values(): for zm_client in hass.data[ZONEMINDER_DOMAIN].values():
monitors = zm_client.get_monitors() if not (monitors := zm_client.get_monitors()):
if not monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder") _LOGGER.warning("Could not fetch monitors from ZoneMinder")
return return