Use set & dict literals (#33636)

Co-authored-by: Daniel Høyer Iversen <mail@dahoiv.net>
This commit is contained in:
Franck Nijhof 2020-04-04 20:05:15 +02:00 committed by GitHub
parent d85222ad80
commit 7d3c974747
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 89 additions and 80 deletions

View file

@ -309,7 +309,7 @@ async def async_mount_local_lib_path(config_dir: str) -> str:
def _get_domains(hass: core.HomeAssistant, config: Dict[str, Any]) -> Set[str]: def _get_domains(hass: core.HomeAssistant, config: Dict[str, Any]) -> Set[str]:
"""Get domains of components to set up.""" """Get domains of components to set up."""
# Filter out the repeating and common config section [homeassistant] # Filter out the repeating and common config section [homeassistant]
domains = set(key.split(" ")[0] for key in config.keys() if key != core.DOMAIN) domains = {key.split(" ")[0] for key in config.keys() if key != core.DOMAIN}
# Add config entry domains # Add config entry domains
if not hass.config.safe_mode: if not hass.config.safe_mode:

View file

@ -214,11 +214,11 @@ class AugustData(AugustSubscriberMixin):
await self._api.async_get_doorbells(self._august_gateway.access_token) or [] await self._api.async_get_doorbells(self._august_gateway.access_token) or []
) )
self._doorbells_by_id = dict((device.device_id, device) for device in doorbells) self._doorbells_by_id = {device.device_id: device for device in doorbells}
self._locks_by_id = dict((device.device_id, device) for device in locks) self._locks_by_id = {device.device_id: device for device in locks}
self._house_ids = set( self._house_ids = {
device.house_id for device in itertools.chain(locks, doorbells) device.house_id for device in itertools.chain(locks, doorbells)
) }
await self._async_refresh_device_detail_by_ids( await self._async_refresh_device_detail_by_ids(
[device.device_id for device in itertools.chain(locks, doorbells)] [device.device_id for device in itertools.chain(locks, doorbells)]

View file

@ -303,11 +303,11 @@ class BayesianBinarySensor(BinarySensorDevice):
return { return {
ATTR_OBSERVATIONS: list(self.current_observations.values()), ATTR_OBSERVATIONS: list(self.current_observations.values()),
ATTR_OCCURRED_OBSERVATION_ENTITIES: list( ATTR_OCCURRED_OBSERVATION_ENTITIES: list(
set( {
obs.get("entity_id") obs.get("entity_id")
for obs in self.current_observations.values() for obs in self.current_observations.values()
if obs is not None if obs is not None
) }
), ),
ATTR_PROBABILITY: round(self.probability, 2), ATTR_PROBABILITY: round(self.probability, 2),
ATTR_PROBABILITY_THRESHOLD: self._probability_threshold, ATTR_PROBABILITY_THRESHOLD: self._probability_threshold,

View file

@ -61,8 +61,8 @@ SENSOR_TYPES = {
SENSOR_AQ: ["Air Quality", UNIT_PERCENTAGE], SENSOR_AQ: ["Air Quality", UNIT_PERCENTAGE],
} }
DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS, SENSOR_AQ] DEFAULT_MONITORED = [SENSOR_TEMP, SENSOR_HUMID, SENSOR_PRESS, SENSOR_AQ]
OVERSAMPLING_VALUES = set([0, 1, 2, 4, 8, 16]) OVERSAMPLING_VALUES = {0, 1, 2, 4, 8, 16}
FILTER_VALUES = set([0, 1, 3, 7, 15, 31, 63, 127]) FILTER_VALUES = {0, 1, 3, 7, 15, 31, 63, 127}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {

View file

@ -30,9 +30,9 @@ def discover_chromecast(hass: HomeAssistant, info: ChromecastInfo):
if info.uuid is not None: if info.uuid is not None:
# Remove previous cast infos with same uuid from known chromecasts. # Remove previous cast infos with same uuid from known chromecasts.
same_uuid = set( same_uuid = {
x for x in hass.data[KNOWN_CHROMECAST_INFO_KEY] if info.uuid == x.uuid x for x in hass.data[KNOWN_CHROMECAST_INFO_KEY] if info.uuid == x.uuid
) }
hass.data[KNOWN_CHROMECAST_INFO_KEY] -= same_uuid hass.data[KNOWN_CHROMECAST_INFO_KEY] -= same_uuid
hass.data[KNOWN_CHROMECAST_INFO_KEY].add(info) hass.data[KNOWN_CHROMECAST_INFO_KEY].add(info)

View file

@ -11,9 +11,9 @@ from .const import CONF_LISTEN_PORT, DEFAULT_NAME, DEFAULT_PORT, DOMAIN
@callback @callback
def configured_servers(hass): def configured_servers(hass):
"""Return a set of the configured servers.""" """Return a set of the configured servers."""
return set( return {
entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN) entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN)
) }
@config_entries.HANDLERS.register(DOMAIN) @config_entries.HANDLERS.register(DOMAIN)

View file

@ -24,10 +24,10 @@ _LOGGER = logging.getLogger(__name__)
@callback @callback
def configured_instances(hass): def configured_instances(hass):
"""Return a set of configured GeoNet NZ Volcano instances.""" """Return a set of configured GeoNet NZ Volcano instances."""
return set( return {
f"{entry.data[CONF_LATITUDE]}, {entry.data[CONF_LONGITUDE]}" f"{entry.data[CONF_LATITUDE]}, {entry.data[CONF_LONGITUDE]}"
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
class GeonetnzVolcanoFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): class GeonetnzVolcanoFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -262,7 +262,7 @@ async def async_devices_reachable(hass, data: RequestData, payload):
https://developers.google.com/actions/smarthome/create#actiondevicesdisconnect https://developers.google.com/actions/smarthome/create#actiondevicesdisconnect
""" """
google_ids = set(dev["id"] for dev in (data.devices or [])) google_ids = {dev["id"] for dev in (data.devices or [])}
return { return {
"devices": [ "devices": [

View file

@ -659,9 +659,9 @@ class GTFSDepartureSensor(Entity):
@staticmethod @staticmethod
def dict_for_table(resource: Any) -> dict: def dict_for_table(resource: Any) -> dict:
"""Return a dictionary for the SQLAlchemy resource given.""" """Return a dictionary for the SQLAlchemy resource given."""
return dict( return {
(col, getattr(resource, col)) for col in resource.__table__.columns.keys() col: getattr(resource, col) for col in resource.__table__.columns.keys()
) }
def append_keys(self, resource: dict, prefix: Optional[str] = None) -> None: def append_keys(self, resource: dict, prefix: Optional[str] = None) -> None:
"""Properly format key val pairs to append to attributes.""" """Properly format key val pairs to append to attributes."""

View file

@ -50,10 +50,10 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
accesspoints = config.get(DOMAIN, []) accesspoints = config.get(DOMAIN, [])
for conf in accesspoints: for conf in accesspoints:
if conf[CONF_ACCESSPOINT] not in set( if conf[CONF_ACCESSPOINT] not in {
entry.data[HMIPC_HAPID] entry.data[HMIPC_HAPID]
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
): }:
hass.async_add_job( hass.async_add_job(
hass.config_entries.flow.async_init( hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,

View file

@ -70,9 +70,9 @@ async def async_setup(hass, config):
bridges = conf[CONF_BRIDGES] bridges = conf[CONF_BRIDGES]
configured_hosts = set( configured_hosts = {
entry.data.get("host") for entry in hass.config_entries.async_entries(DOMAIN) entry.data.get("host") for entry in hass.config_entries.async_entries(DOMAIN)
) }
for bridge_conf in bridges: for bridge_conf in bridges:
host = bridge_conf[CONF_HOST] host = bridge_conf[CONF_HOST]

View file

@ -16,9 +16,9 @@ from .const import CONF_ZIP_CODE, DOMAIN
@callback @callback
def configured_instances(hass): def configured_instances(hass):
"""Return a set of configured IQVIA instances.""" """Return a set of configured IQVIA instances."""
return set( return {
entry.data[CONF_ZIP_CODE] for entry in hass.config_entries.async_entries(DOMAIN) entry.data[CONF_ZIP_CODE] for entry in hass.config_entries.async_entries(DOMAIN)
) }
@config_entries.HANDLERS.register(DOMAIN) @config_entries.HANDLERS.register(DOMAIN)

View file

@ -22,10 +22,10 @@ from .const import CONF_SENSOR_ID, DEFAULT_SCAN_INTERVAL, DOMAIN
@callback @callback
def configured_sensors(hass): def configured_sensors(hass):
"""Return a set of configured Luftdaten sensors.""" """Return a set of configured Luftdaten sensors."""
return set( return {
entry.data[CONF_SENSOR_ID] entry.data[CONF_SENSOR_ID]
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
@callback @callback

View file

@ -90,13 +90,11 @@ class MoldIndicator(Entity):
self._calib_factor = calib_factor self._calib_factor = calib_factor
self._is_metric = is_metric self._is_metric = is_metric
self._available = False self._available = False
self._entities = set( self._entities = {
[ self._indoor_temp_sensor,
self._indoor_temp_sensor, self._indoor_humidity_sensor,
self._indoor_humidity_sensor, self._outdoor_temp_sensor,
self._outdoor_temp_sensor, }
]
)
self._dewpoint = None self._dewpoint = None
self._indoor_temp = None self._indoor_temp = None

View file

@ -19,13 +19,13 @@ from .const import DOMAIN
@callback @callback
def configured_instances(hass): def configured_instances(hass):
"""Return a set of configured OpenUV instances.""" """Return a set of configured OpenUV instances."""
return set( return {
"{}, {}".format( "{}, {}".format(
entry.data.get(CONF_LATITUDE, hass.config.latitude), entry.data.get(CONF_LATITUDE, hass.config.latitude),
entry.data.get(CONF_LONGITUDE, hass.config.longitude), entry.data.get(CONF_LONGITUDE, hass.config.longitude),
) )
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
@config_entries.HANDLERS.register(DOMAIN) @config_entries.HANDLERS.register(DOMAIN)

View file

@ -87,7 +87,7 @@ class PioneerDevice(MediaPlayerDevice):
self._muted = False self._muted = False
self._selected_source = "" self._selected_source = ""
self._source_name_to_number = sources self._source_name_to_number = sources
self._source_number_to_name = dict((v, k) for k, v in sources.items()) self._source_number_to_name = {v: k for k, v in sources.items()}
@classmethod @classmethod
def telnet_request(cls, telnet, command, expected_prefix): def telnet_request(cls, telnet, command, expected_prefix):

View file

@ -43,10 +43,10 @@ _LOGGER = logging.getLogger(__package__)
@callback @callback
def configured_servers(hass): def configured_servers(hass):
"""Return a set of the configured Plex servers.""" """Return a set of the configured Plex servers."""
return set( return {
entry.data[CONF_SERVER_IDENTIFIER] entry.data[CONF_SERVER_IDENTIFIER]
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
class PlexFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): class PlexFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -32,30 +32,41 @@ FOLDER = "python_scripts"
CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema(dict)}, extra=vol.ALLOW_EXTRA) CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema(dict)}, extra=vol.ALLOW_EXTRA)
ALLOWED_HASS = set(["bus", "services", "states"]) ALLOWED_HASS = {"bus", "services", "states"}
ALLOWED_EVENTBUS = set(["fire"]) ALLOWED_EVENTBUS = {"fire"}
ALLOWED_STATEMACHINE = set( ALLOWED_STATEMACHINE = {
["entity_ids", "all", "get", "is_state", "is_state_attr", "remove", "set"] "entity_ids",
) "all",
ALLOWED_SERVICEREGISTRY = set(["services", "has_service", "call"]) "get",
ALLOWED_TIME = set( "is_state",
["sleep", "strftime", "strptime", "gmtime", "localtime", "ctime", "time", "mktime"] "is_state_attr",
) "remove",
ALLOWED_DATETIME = set(["date", "time", "datetime", "timedelta", "tzinfo"]) "set",
ALLOWED_DT_UTIL = set( }
[ ALLOWED_SERVICEREGISTRY = {"services", "has_service", "call"}
"utcnow", ALLOWED_TIME = {
"now", "sleep",
"as_utc", "strftime",
"as_timestamp", "strptime",
"as_local", "gmtime",
"utc_from_timestamp", "localtime",
"start_of_local_day", "ctime",
"parse_datetime", "time",
"parse_date", "mktime",
"get_age", }
] ALLOWED_DATETIME = {"date", "time", "datetime", "timedelta", "tzinfo"}
) ALLOWED_DT_UTIL = {
"utcnow",
"now",
"as_utc",
"as_timestamp",
"as_local",
"utc_from_timestamp",
"start_of_local_day",
"parse_datetime",
"parse_date",
"get_age",
}
class ScriptError(HomeAssistantError): class ScriptError(HomeAssistantError):

View file

@ -15,10 +15,10 @@ from .const import DOMAIN, HOME_LOCATION_NAME
@callback @callback
def smhi_locations(hass: HomeAssistant): def smhi_locations(hass: HomeAssistant):
"""Return configurations of SMHI component.""" """Return configurations of SMHI component."""
return set( return {
(slugify(entry.data[CONF_NAME])) (slugify(entry.data[CONF_NAME]))
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
@config_entries.HANDLERS.register(DOMAIN) @config_entries.HANDLERS.register(DOMAIN)

View file

@ -14,10 +14,10 @@ from .const import CONF_SITE_ID, DEFAULT_NAME, DOMAIN
@callback @callback
def solaredge_entries(hass: HomeAssistant): def solaredge_entries(hass: HomeAssistant):
"""Return the site_ids for the domain.""" """Return the site_ids for the domain."""
return set( return {
(entry.data[CONF_SITE_ID]) (entry.data[CONF_SITE_ID])
for entry in hass.config_entries.async_entries(DOMAIN) for entry in hass.config_entries.async_entries(DOMAIN)
) }
class SolarEdgeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class SolarEdgeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -19,9 +19,9 @@ _LOGGER = logging.getLogger(__name__)
@callback @callback
def solarlog_entries(hass: HomeAssistant): def solarlog_entries(hass: HomeAssistant):
"""Return the hosts already configured.""" """Return the hosts already configured."""
return set( return {
entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN) entry.data[CONF_HOST] for entry in hass.config_entries.async_entries(DOMAIN)
) }
class SolarLogConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class SolarLogConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -1109,7 +1109,7 @@ class SonosEntity(MediaPlayerDevice):
entity.restore() entity.restore()
# Find all affected players # Find all affected players
entities = set(e for e in entities if e._soco_snapshot) entities = {e for e in entities if e._soco_snapshot}
if with_group: if with_group:
for entity in [e for e in entities if e._snapshot_group]: for entity in [e for e in entities if e._snapshot_group]:
entities.update(entity._snapshot_group) entities.update(entity._snapshot_group)

View file

@ -33,7 +33,7 @@ DATA_SCHEMA = vol.Schema(
@callback @callback
def configured_instances(hass): def configured_instances(hass):
"""Return a set of configured Tesla instances.""" """Return a set of configured Tesla instances."""
return set(entry.title for entry in hass.config_entries.async_entries(DOMAIN)) return {entry.title for entry in hass.config_entries.async_entries(DOMAIN)}
class TeslaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class TeslaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -31,9 +31,9 @@ _LOGGER = logging.getLogger(__name__)
@callback @callback
def configured_displays(hass): def configured_displays(hass):
"""Return a set of configured Toon displays.""" """Return a set of configured Toon displays."""
return set( return {
entry.data[CONF_DISPLAY] for entry in hass.config_entries.async_entries(DOMAIN) entry.data[CONF_DISPLAY] for entry in hass.config_entries.async_entries(DOMAIN)
) }
@config_entries.HANDLERS.register(DOMAIN) @config_entries.HANDLERS.register(DOMAIN)

View file

@ -13,9 +13,9 @@ from .const import DOMAIN
@callback @callback
def velbus_entries(hass: HomeAssistant): def velbus_entries(hass: HomeAssistant):
"""Return connections for Velbus domain.""" """Return connections for Velbus domain."""
return set( return {
(entry.data[CONF_PORT]) for entry in hass.config_entries.async_entries(DOMAIN) (entry.data[CONF_PORT]) for entry in hass.config_entries.async_entries(DOMAIN)
) }
class VelbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): class VelbusConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):

View file

@ -870,11 +870,11 @@ class ConfigFlow(data_entry_flow.FlowHandler):
def _async_current_ids(self, include_ignore: bool = True) -> Set[Optional[str]]: def _async_current_ids(self, include_ignore: bool = True) -> Set[Optional[str]]:
"""Return current unique IDs.""" """Return current unique IDs."""
assert self.hass is not None assert self.hass is not None
return set( return {
entry.unique_id entry.unique_id
for entry in self.hass.config_entries.async_entries(self.handler) for entry in self.hass.config_entries.async_entries(self.handler)
if include_ignore or entry.source != SOURCE_IGNORE if include_ignore or entry.source != SOURCE_IGNORE
) }
@callback @callback
def _async_in_progress(self) -> List[Dict]: def _async_in_progress(self) -> List[Dict]:

View file

@ -107,7 +107,7 @@ async def async_check_ha_config_file(hass: HomeAssistant) -> HomeAssistantConfig
core_config.pop(CONF_PACKAGES, None) core_config.pop(CONF_PACKAGES, None)
# Filter out repeating config sections # Filter out repeating config sections
components = set(key.split(" ")[0] for key in config.keys()) components = {key.split(" ")[0] for key in config.keys()}
# Process and validate config # Process and validate config
for domain in components: for domain in components:

View file

@ -123,11 +123,11 @@ class RestoreStateData:
now = dt_util.utcnow() now = dt_util.utcnow()
all_states = self.hass.states.async_all() all_states = self.hass.states.async_all()
# Entities currently backed by an entity object # Entities currently backed by an entity object
current_entity_ids = set( current_entity_ids = {
state.entity_id state.entity_id
for state in all_states for state in all_states
if not state.attributes.get(entity_registry.ATTR_RESTORED) if not state.attributes.get(entity_registry.ATTR_RESTORED)
) }
# Start with the currently registered states # Start with the currently registered states
stored_states = [ stored_states = [