Update pylint to 2.11.1 (#56364)

This commit is contained in:
Marc Mueller 2021-09-18 13:52:59 +02:00 committed by GitHub
parent 476d04e2fb
commit 48bada5a18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 77 additions and 43 deletions

View File

@ -142,6 +142,7 @@ class AmbiclimateAuthCallbackView(HomeAssistantView):
async def get(self, request: web.Request) -> str:
"""Receive authorization token."""
# pylint: disable=no-self-use
code = request.query.get("code")
if code is None:
return "No code"

View File

@ -358,6 +358,7 @@ def adb_decorator(override_available=False):
@functools.wraps(func)
async def _adb_exception_catcher(self, *args, **kwargs):
"""Call an ADB-related method and catch exceptions."""
# pylint: disable=protected-access
if not self.available and not override_available:
return None

View File

@ -93,6 +93,7 @@ class APIEventStream(HomeAssistantView):
async def get(self, request):
"""Provide a streaming interface for the event bus."""
# pylint: disable=no-self-use
if not request["hass_user"].is_admin:
raise Unauthorized()
hass = request.app["hass"]
@ -414,6 +415,7 @@ class APIErrorLog(HomeAssistantView):
async def get(self, request):
"""Retrieve API error log."""
# pylint: disable=no-self-use
if not request["hass_user"].is_admin:
raise Unauthorized()
return web.FileResponse(request.app["hass"].data[DATA_LOGGING])

View File

@ -264,6 +264,8 @@ class TokenView(HomeAssistantView):
async def _async_handle_revoke_token(self, hass, data):
"""Handle revoke token request."""
# pylint: disable=no-self-use
# OAuth 2.0 Token Revocation [RFC7009]
# 2.2 The authorization server responds with HTTP status code 200
# if the token has been revoked successfully or if the client

View File

@ -157,6 +157,7 @@ class LoginFlowIndexView(HomeAssistantView):
async def get(self, request):
"""Do not allow index of flows in progress."""
# pylint: disable=no-self-use
return web.Response(status=HTTP_METHOD_NOT_ALLOWED)
@RequestDataValidator(

View File

@ -74,6 +74,7 @@ class AwairDataUpdateCoordinator(DataUpdateCoordinator):
async def _fetch_air_data(self, device):
"""Fetch latest air quality data."""
# pylint: disable=no-self-use
LOGGER.debug("Fetching data for %s", device.uuid)
air_data = await device.air_data_latest()
LOGGER.debug(air_data)

View File

@ -316,7 +316,7 @@ class DomainBlueprints:
raise FileAlreadyExists(self.domain, blueprint_path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(blueprint.yaml())
path.write_text(blueprint.yaml(), encoding="utf-8")
async def async_add_blueprint(
self, blueprint: Blueprint, blueprint_path: str

View File

@ -434,6 +434,7 @@ class Camera(Entity):
async def stream_source(self) -> str | None:
"""Return the source of the stream."""
# pylint: disable=no-self-use
return None
def camera_image(

View File

@ -116,6 +116,7 @@ class ConfigManagerFlowIndexView(FlowManagerIndexView):
async def get(self, request):
"""Not implemented."""
# pylint: disable=no-self-use
raise aiohttp.web_exceptions.HTTPMethodNotAllowed("GET", ["POST"])
# pylint: disable=arguments-differ

View File

@ -17,10 +17,12 @@ class AbstractConversationAgent(ABC):
async def async_get_onboarding(self):
"""Get onboard data."""
# pylint: disable=no-self-use
return None
async def async_set_onboarding(self, shown):
"""Set onboard data."""
# pylint: disable=no-self-use
return True
@abstractmethod

View File

@ -309,10 +309,7 @@ class DenonDevice(MediaPlayerEntity):
@property
def media_content_type(self):
"""Content type of current playing media."""
if (
self._receiver.state == STATE_PLAYING
or self._receiver.state == STATE_PAUSED
):
if self._receiver.state in (STATE_PLAYING, STATE_PAUSED):
return MEDIA_TYPE_MUSIC
return MEDIA_TYPE_CHANNEL

View File

@ -324,6 +324,7 @@ class DoorBirdRequestView(HomeAssistantView):
async def get(self, request, event):
"""Respond to requests from the device."""
# pylint: disable=no-self-use
hass = request.app["hass"]
token = request.query.get("token")

View File

@ -676,7 +676,7 @@ class Thermostat(ClimateEntity):
heatCoolMinDelta property.
https://www.ecobee.com/home/developer/api/examples/ex5.shtml
"""
if self.hvac_mode == HVAC_MODE_HEAT or self.hvac_mode == HVAC_MODE_COOL:
if self.hvac_mode in (HVAC_MODE_HEAT, HVAC_MODE_COOL):
heat_temp = temp
cool_temp = temp
else:

View File

@ -65,8 +65,9 @@ class ElkThermostat(ElkEntity, ClimateEntity):
@property
def target_temperature(self):
"""Return the temperature we are trying to reach."""
if (self._element.mode == ThermostatMode.HEAT.value) or (
self._element.mode == ThermostatMode.EMERGENCY_HEAT.value
if self._element.mode in (
ThermostatMode.HEAT.value,
ThermostatMode.EMERGENCY_HEAT.value,
):
return self._element.heat_setpoint
if self._element.mode == ThermostatMode.COOL.value:

View File

@ -805,6 +805,7 @@ def esphome_state_property(func: _PropT) -> _PropT:
@property # type: ignore[misc]
@functools.wraps(func)
def _wrapper(self): # type: ignore[no-untyped-def]
# pylint: disable=protected-access
if not self._has_state:
return None
val = func(self)

View File

@ -136,7 +136,7 @@ class FibaroThermostat(FibaroDevice, ClimateEntity):
"value" in device.properties
or "heatingThermostatSetpoint" in device.properties
)
and (device.properties.unit == "C" or device.properties.unit == "F")
and device.properties.unit in ("C", "F")
):
self._temp_sensor_device = FibaroDevice(device)
tempunit = device.properties.unit

View File

@ -114,9 +114,9 @@ class FritzboxThermostat(FritzBoxEntity, ClimateEntity):
@property
def hvac_mode(self) -> str:
"""Return the current operation mode."""
if (
self.device.target_temperature == OFF_REPORT_SET_TEMPERATURE
or self.device.target_temperature == OFF_API_TEMPERATURE
if self.device.target_temperature in (
OFF_REPORT_SET_TEMPERATURE,
OFF_API_TEMPERATURE,
):
return HVAC_MODE_OFF

View File

@ -963,6 +963,7 @@ class HomeKitPairingQRView(HomeAssistantView):
async def get(self, request):
"""Retrieve the pairing QRCode image."""
# pylint: disable=no-self-use
if not request.query_string:
raise Unauthorized()
entry_id, secret = request.query_string.split("-")

View File

@ -59,6 +59,7 @@ class HomematicipAuth:
async def get_auth(self, hass: HomeAssistant, hapid, pin):
"""Create a HomematicIP access point object."""
# pylint: disable=no-self-use
auth = AsyncAuth(hass.loop, async_get_clientsession(hass))
try:
await auth.init(hapid)

View File

@ -69,6 +69,7 @@ class HuisbaasjeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
# pylint: disable=no-self-use
username = user_input[CONF_USERNAME]
password = user_input[CONF_PASSWORD]

View File

@ -179,6 +179,7 @@ def state(new_state):
def wrapper(self, **kwargs):
"""Wrap a group state change."""
# pylint: disable=protected-access
pipeline = Pipeline()
transition_time = DEFAULT_TRANSITION

View File

@ -69,10 +69,12 @@ class LovelaceConfig(ABC):
async def async_save(self, config):
"""Save config."""
# pylint: disable=no-self-use
raise HomeAssistantError("Not supported")
async def async_delete(self):
"""Delete config."""
# pylint: disable=no-self-use
raise HomeAssistantError("Not supported")
@callback

View File

@ -412,7 +412,7 @@ class ManualAlarm(alarm.AlarmControlPanelEntity, RestoreEntity):
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if self.state == STATE_ALARM_PENDING or self.state == STATE_ALARM_ARMING:
if self.state in (STATE_ALARM_PENDING, STATE_ALARM_ARMING):
return {
ATTR_PREVIOUS_STATE: self._previous_state,
ATTR_NEXT_STATE: self._state,
@ -430,10 +430,7 @@ class ManualAlarm(alarm.AlarmControlPanelEntity, RestoreEntity):
state = await self.async_get_last_state()
if state:
if (
(
state.state == STATE_ALARM_PENDING
or state.state == STATE_ALARM_ARMING
)
state.state in (STATE_ALARM_PENDING, STATE_ALARM_ARMING)
and hasattr(state, "attributes")
and state.attributes[ATTR_PREVIOUS_STATE]
):

View File

@ -507,6 +507,7 @@ class MediaPlayerEntity(Entity):
Must be implemented by integration.
"""
# pylint: disable=no-self-use
return None, None
@property

View File

@ -60,7 +60,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.hass.helpers.aiohttp_client.async_get_clientsession(),
)
except ClientResponseError as err:
if err.status == HTTP_UNAUTHORIZED or err.status == HTTP_FORBIDDEN:
if err.status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN):
return self.async_abort(reason="invalid_auth")
return self.async_abort(reason="cannot_connect")
except (asyncio.TimeoutError, ClientError):

View File

@ -222,6 +222,7 @@ class NestCamera(Camera):
self, trait: EventImageGenerator
) -> bytes | None:
"""Return image bytes for an active event."""
# pylint: disable=no-self-use
try:
event_image = await trait.generate_active_event_image()
except GoogleNestException as err:

View File

@ -83,9 +83,9 @@ class WeatherUpdateCoordinator(DataUpdateCoordinator):
async def _get_owm_weather(self):
"""Poll weather data from OWM."""
if (
self._forecast_mode == FORECAST_MODE_ONECALL_HOURLY
or self._forecast_mode == FORECAST_MODE_ONECALL_DAILY
if self._forecast_mode in (
FORECAST_MODE_ONECALL_HOURLY,
FORECAST_MODE_ONECALL_DAILY,
):
weather = await self.hass.async_add_executor_job(
self._owm_client.one_call, self._latitude, self._longitude

View File

@ -370,7 +370,7 @@ async def async_handle_node_update(hass: HomeAssistant, node: OZWNode):
return
# update device in device registry with (updated) info
for item in dev_registry.devices.values():
if item.id != device.id and item.via_device_id != device.id:
if device.id not in (item.id, item.via_device_id):
continue
dev_name = create_device_name(node)
dev_registry.async_update_device(

View File

@ -422,6 +422,7 @@ class PlexAuthorizationCallbackView(HomeAssistantView):
async def get(self, request):
"""Receive authorization confirmation."""
# pylint: disable=no-self-use
hass = request.app["hass"]
await hass.config_entries.flow.async_configure(
flow_id=request.query["flow_id"], user_input=None

View File

@ -62,7 +62,11 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
def get_cpu_temp():
"""Get CPU temperature."""
t_cpu = Path("/sys/class/thermal/thermal_zone0/temp").read_text().strip()
t_cpu = (
Path("/sys/class/thermal/thermal_zone0/temp")
.read_text(encoding="utf-8")
.strip()
)
return float(t_cpu) * 0.001

View File

@ -93,6 +93,7 @@ class SmartTubController:
return data
async def _get_spa_data(self, spa):
# pylint: disable=no-self-use
full_status, reminders, errors = await asyncio.gather(
spa.get_status_full(),
spa.get_reminders(),

View File

@ -903,10 +903,7 @@ class SonosSpeaker:
for speaker in (s for s in speakers if s.snapshot_group):
assert speaker.snapshot_group is not None
if speaker.snapshot_group[0] == speaker:
if (
speaker.snapshot_group != speaker.sonos_group
and speaker.snapshot_group != [speaker]
):
if speaker.snapshot_group not in (speaker.sonos_group, [speaker]):
speaker.join(speaker.snapshot_group)
groups.append(speaker.snapshot_group.copy())

View File

@ -207,6 +207,7 @@ def spotify_exception_handler(func):
"""
def wrapper(self, *args, **kwargs):
# pylint: disable=protected-access
try:
result = func(self, *args, **kwargs)
self._attr_available = True

View File

@ -170,7 +170,6 @@ class Segment:
# Preload hints help save round trips by informing the client about the next part.
# The next part will usually be in this segment but will be first part of the next
# segment if this segment is already complete.
# pylint: disable=undefined-loop-variable
if self.complete: # Next part belongs to next segment
sequence = self.sequence + 1
part_num = 0

View File

@ -111,11 +111,9 @@ class TankUtilitySensor(SensorEntity):
try:
data = tank_monitor.get_device_data(self._token, self.device)
except requests.exceptions.HTTPError as http_error:
if (
http_error.response.status_code
== requests.codes.unauthorized # pylint: disable=no-member
or http_error.response.status_code
== requests.codes.bad_request # pylint: disable=no-member
if http_error.response.status_code in (
requests.codes.unauthorized, # pylint: disable=no-member
requests.codes.bad_request, # pylint: disable=no-member
):
_LOGGER.info("Getting new token")
self._token = auth.get_token(self._email, self._password, force=True)

View File

@ -271,7 +271,7 @@ class Timer(RestoreEntity):
newduration = duration
event = EVENT_TIMER_STARTED
if self._state == STATUS_ACTIVE or self._state == STATUS_PAUSED:
if self._state in (STATUS_ACTIVE, STATUS_PAUSED):
event = EVENT_TIMER_RESTARTED
self._state = STATUS_ACTIVE

View File

@ -131,6 +131,7 @@ class WebhookView(HomeAssistantView):
async def _handle(self, request: Request, webhook_id):
"""Handle webhook call."""
# pylint: disable=no-self-use
_LOGGER.debug("Handling webhook %s payload for %s", request.method, webhook_id)
hass = request.app["hass"]
return await async_handle_webhook(hass, webhook_id, request)

View File

@ -304,9 +304,7 @@ class LgWebOSMediaPlayerEntity(MediaPlayerEntity):
"""Flag media player features that are supported."""
supported = SUPPORT_WEBOSTV
if (self._client.sound_output == "external_arc") or (
self._client.sound_output == "external_speaker"
):
if self._client.sound_output in ("external_arc", "external_speaker"):
supported = supported | SUPPORT_WEBOSTV_VOLUME
elif self._client.sound_output != "lineout":
supported = supported | SUPPORT_WEBOSTV_VOLUME | SUPPORT_VOLUME_SET

View File

@ -42,6 +42,7 @@ class WebsocketAPIView(HomeAssistantView):
async def get(self, request: web.Request) -> web.WebSocketResponse:
"""Handle an incoming websocket connection."""
# pylint: disable=no-self-use
return await WebSocketHandler(request.app["hass"], request).async_handle()

View File

@ -9,7 +9,7 @@ from whirlpool.auth import Auth
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from .const import DOMAIN # pylint: disable=unused-import
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)

View File

@ -640,6 +640,7 @@ class DataManager:
Withings' API occasionally and incorrectly throws errors. Retrying the call tends to work.
"""
# pylint: disable=no-self-use
exception = None
for attempt in range(1, attempts + 1):
_LOGGER.debug("Attempt %s of %s", attempt, attempts)

View File

@ -268,7 +268,7 @@ class ZWaveClimateBase(ZWaveDeviceEntity, ClimateEntity):
# Default operation mode
for mode in DEFAULT_HVAC_MODES:
if mode in self._hvac_mapping.keys():
if mode in self._hvac_mapping:
self._default_hvac_mode = mode
break
@ -291,14 +291,14 @@ class ZWaveClimateBase(ZWaveDeviceEntity, ClimateEntity):
# The current mode is not a hvac mode
if (
"heat" in current_mode.lower()
and HVAC_MODE_HEAT in self._hvac_mapping.keys()
and HVAC_MODE_HEAT in self._hvac_mapping
):
# The current preset modes maps to HVAC_MODE_HEAT
_LOGGER.debug("Mapped to HEAT")
self._hvac_mode = HVAC_MODE_HEAT
elif (
"cool" in current_mode.lower()
and HVAC_MODE_COOL in self._hvac_mapping.keys()
and HVAC_MODE_COOL in self._hvac_mapping
):
# The current preset modes maps to HVAC_MODE_COOL
_LOGGER.debug("Mapped to COOL")

View File

@ -1274,6 +1274,7 @@ class DumpView(HomeAssistantView):
async def get(self, request: web.Request, config_entry_id: str) -> web.Response:
"""Dump the state of Z-Wave."""
# pylint: disable=no-self-use
if not request["hass_user"].is_admin:
raise Unauthorized()
hass = request.app["hass"]

View File

@ -471,6 +471,7 @@ class ZWaveNodeStatusSensor(SensorEntity):
async def async_poll_value(self, _: bool) -> None:
"""Poll a value."""
# pylint: disable=no-self-use
raise ValueError("There is no value to poll for this entity")
@callback

View File

@ -359,6 +359,7 @@ class ZWaveServices:
async def async_set_config_parameter(self, service: ServiceCall) -> None:
"""Set a config value on a node."""
# pylint: disable=no-self-use
nodes = service.data[const.ATTR_NODES]
property_or_property_name = service.data[const.ATTR_CONFIG_PARAMETER]
property_key = service.data.get(const.ATTR_CONFIG_PARAMETER_BITMASK)
@ -386,6 +387,7 @@ class ZWaveServices:
self, service: ServiceCall
) -> None:
"""Bulk set multiple partial config values on a node."""
# pylint: disable=no-self-use
nodes = service.data[const.ATTR_NODES]
property_ = service.data[const.ATTR_CONFIG_PARAMETER]
new_value = service.data[const.ATTR_CONFIG_VALUE]
@ -420,6 +422,7 @@ class ZWaveServices:
async def async_set_value(self, service: ServiceCall) -> None:
"""Set a value on a node."""
# pylint: disable=no-self-use
nodes = service.data[const.ATTR_NODES]
command_class = service.data[const.ATTR_COMMAND_CLASS]
property_ = service.data[const.ATTR_PROPERTY]
@ -496,5 +499,6 @@ class ZWaveServices:
async def async_ping(self, service: ServiceCall) -> None:
"""Ping node(s)."""
# pylint: disable=no-self-use
nodes: set[ZwaveNode] = service.data[const.ATTR_NODES]
await asyncio.gather(*(node.async_ping() for node in nodes))

View File

@ -488,6 +488,7 @@ class HomeAssistant:
async def _await_and_log_pending(self, pending: Iterable[Awaitable[Any]]) -> None:
"""Await and log tasks that take a long time."""
# pylint: disable=no-self-use
wait_time = 0
while pending:
_, pending = await asyncio.wait(pending, timeout=BLOCK_LOG_TIMEOUT)

View File

@ -406,6 +406,7 @@ class OAuth2AuthorizeCallbackView(http.HomeAssistantView):
async def get(self, request: web.Request) -> web.Response:
"""Receive authorization code."""
# pylint: disable=no-self-use
if "code" not in request.query or "state" not in request.query:
return web.Response(
text=f"Missing code or state parameter in {request.url}"

View File

@ -17,6 +17,7 @@ forced_separate = [
combine_as_imports = true
[tool.pylint.MASTER]
py-version = "3.8"
ignore = [
"tests",
]
@ -69,9 +70,11 @@ good-names = [
# inconsistent-return-statements - doesn't handle raise
# too-many-ancestors - it's too strict.
# wrong-import-order - isort guards this
# consider-using-f-string - str.format sometimes more readable
# ---
# Enable once current issues are fixed:
# consider-using-namedtuple-or-dataclass (Pylint CodeStyle extension)
# consider-using-assignment-expr (Pylint CodeStyle extension)
disable = [
"format",
"abstract-class-little-used",
@ -94,7 +97,9 @@ disable = [
"too-many-boolean-expressions",
"unused-argument",
"wrong-import-order",
"consider-using-f-string",
"consider-using-namedtuple-or-dataclass",
"consider-using-assignment-expr",
]
enable = [
#"useless-suppression", # temporarily every now and then to clean them up
@ -120,9 +125,11 @@ overgeneral-exceptions = [
]
[tool.pylint.TYPING]
py-version = "3.8"
runtime-typing = false
[tool.pylint.CODE_STYLE]
max-line-length-suggestions = 72
[tool.pytest.ini_options]
testpaths = [
"tests",

View File

@ -13,7 +13,7 @@ jsonpickle==1.4.1
mock-open==1.4.0
mypy==0.910
pre-commit==2.14.0
pylint==2.10.2
pylint==2.11.1
pipdeptree==1.0.0
pylint-strict-informational==0.1
pytest-aiohttp==0.3.0