Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update pylint to 2.8.0 #49637

Merged
merged 9 commits into from
Apr 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions homeassistant/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def daemonize() -> None:
sys.exit(0)

# redirect standard file descriptors to devnull
# pylint: disable=consider-using-with
infd = open(os.devnull)
outfd = open(os.devnull, "a+")
sys.stdout.flush()
Expand Down
5 changes: 1 addition & 4 deletions homeassistant/components/alexa/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,10 +1374,7 @@ async def async_api_seek(hass, config, directive, context):
msg = f"{entity} did not return the current media position."
raise AlexaVideoActionNotPermittedForContentError(msg)

seek_position = int(current_position) + int(position_delta / 1000)

if seek_position < 0:
seek_position = 0
seek_position = max(int(current_position) + int(position_delta / 1000), 0)

media_duration = entity.attributes.get(media_player.ATTR_MEDIA_DURATION)
if media_duration and 0 < int(media_duration) < seek_position:
Expand Down
30 changes: 16 additions & 14 deletions homeassistant/components/command_line/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService
from homeassistant.const import CONF_COMMAND, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.util.process import kill_subprocess

from .const import CONF_COMMAND_TIMEOUT, DEFAULT_TIMEOUT

Expand Down Expand Up @@ -39,17 +40,18 @@ def __init__(self, command, timeout):

def send_message(self, message="", **kwargs):
"""Send a message to a command line."""
try:
proc = subprocess.Popen(
self.command,
universal_newlines=True,
stdin=subprocess.PIPE,
shell=True, # nosec # shell by design
)
proc.communicate(input=message, timeout=self._timeout)
if proc.returncode != 0:
_LOGGER.error("Command failed: %s", self.command)
except subprocess.TimeoutExpired:
_LOGGER.error("Timeout for command: %s", self.command)
except subprocess.SubprocessError:
_LOGGER.error("Error trying to exec command: %s", self.command)
with subprocess.Popen(
self.command,
universal_newlines=True,
stdin=subprocess.PIPE,
shell=True, # nosec # shell by design
) as proc:
try:
proc.communicate(input=message, timeout=self._timeout)
if proc.returncode != 0:
_LOGGER.error("Command failed: %s", self.command)
except subprocess.TimeoutExpired:
_LOGGER.error("Timeout for command: %s", self.command)
kill_subprocess(proc)
except subprocess.SubprocessError:
_LOGGER.error("Error trying to exec command: %s", self.command)
6 changes: 3 additions & 3 deletions homeassistant/components/denonavr/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def __init__(
)
self._available = True

def async_log_errors( # pylint: disable=no-self-argument
def async_log_errors(
func: Coroutine,
) -> Coroutine:
"""
Expand All @@ -168,7 +168,7 @@ async def wrapper(self, *args, **kwargs):
# pylint: disable=protected-access
available = True
try:
return await func(self, *args, **kwargs) # pylint: disable=not-callable
return await func(self, *args, **kwargs)
except AvrTimoutError:
available = False
if self._available is True:
Expand Down Expand Up @@ -203,7 +203,7 @@ async def wrapper(self, *args, **kwargs):
_LOGGER.error(
"Error %s occurred in method %s for Denon AVR receiver",
err,
func.__name__, # pylint: disable=no-member
func.__name__,
exc_info=True,
)
finally:
Expand Down
7 changes: 1 addition & 6 deletions homeassistant/components/devolo_home_control/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@
from homeassistant.helpers.typing import DiscoveryInfoType

from . import configure_mydevolo
from .const import ( # pylint:disable=unused-import
CONF_MYDEVOLO,
DEFAULT_MYDEVOLO,
DOMAIN,
SUPPORTED_MODEL_TYPES,
)
from .const import CONF_MYDEVOLO, DEFAULT_MYDEVOLO, DOMAIN, SUPPORTED_MODEL_TYPES
from .exceptions import CredentialsInvalid


Expand Down
1 change: 1 addition & 0 deletions homeassistant/components/hangouts/hangouts_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ async def _async_send_message(self, message, targets, data):
uri = data.get("image_file")
if self.hass.config.is_allowed_path(uri):
try:
# pylint: disable=consider-using-with
image_file = open(uri, "rb")
except OSError as error:
_LOGGER.error(
Expand Down
1 change: 0 additions & 1 deletion homeassistant/components/met_eireann/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
import homeassistant.helpers.config_validation as cv

# pylint:disable=unused-import
from .const import DOMAIN, HOME_LOCATION_NAME


Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/motioneye/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from homeassistant.helpers.typing import ConfigType

from . import create_motioneye_client
from .const import ( # pylint:disable=unused-import
from .const import (
CONF_ADMIN_PASSWORD,
CONF_ADMIN_USERNAME,
CONF_CONFIG_ENTRY,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/nfandroidtv/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def load_file(
if local_path is not None:
# Check whether path is whitelisted in configuration.yaml
if self.is_allowed_path(local_path):
return open(local_path, "rb")
return open(local_path, "rb") # pylint: disable=consider-using-with
_LOGGER.warning("'%s' is not secure to load data from!", local_path)
else:
_LOGGER.warning("Neither URL nor local path found in params!")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ async def async_process_image(self, image):

alpr = await asyncio.create_subprocess_exec(
*self._cmd,
loop=self.hass.loop,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
Expand Down
11 changes: 4 additions & 7 deletions homeassistant/components/picnic/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Config flow for Picnic integration."""
from __future__ import annotations

import logging
from typing import Tuple

from python_picnic_api import PicnicAPI
from python_picnic_api.session import PicnicAuthError
Expand All @@ -10,11 +11,7 @@
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_PASSWORD, CONF_USERNAME

from .const import ( # pylint: disable=unused-import
CONF_COUNTRY_CODE,
COUNTRY_CODES,
DOMAIN,
)
from .const import CONF_COUNTRY_CODE, COUNTRY_CODES, DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand All @@ -33,7 +30,7 @@ class PicnicHub:
"""Hub class to test user authentication."""

@staticmethod
def authenticate(username, password, country_code) -> Tuple[str, dict]:
def authenticate(username, password, country_code) -> tuple[str, dict]:
"""Test if we can authenticate with the Picnic API."""
picnic = PicnicAPI(username, password, country_code)
return picnic.session.auth_token, picnic.get_user()
Expand Down
13 changes: 7 additions & 6 deletions homeassistant/components/picnic/sensor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Definition of Picnic sensors."""
from __future__ import annotations

from typing import Any, Optional
from typing import Any

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION
Expand Down Expand Up @@ -48,17 +49,17 @@ def __init__(
self._service_unique_id = config_entry.unique_id

@property
def unit_of_measurement(self) -> Optional[str]:
def unit_of_measurement(self) -> str | None:
"""Return the unit this state is expressed in."""
return self.properties.get("unit")

@property
def unique_id(self) -> Optional[str]:
def unique_id(self) -> str | None:
"""Return a unique ID."""
return f"{self._service_unique_id}.{self.sensor_type}"

@property
def name(self) -> Optional[str]:
def name(self) -> str | None:
"""Return the name of the entity."""
return self._to_capitalized_name(self.sensor_type)

Expand All @@ -69,12 +70,12 @@ def state(self) -> StateType:
return self.properties["state"](data_set)

@property
def device_class(self) -> Optional[str]:
def device_class(self) -> str | None:
"""Return the class of this device, from component DEVICE_CLASSES."""
return self.properties.get("class")

@property
def icon(self) -> Optional[str]:
def icon(self) -> str | None:
"""Return the icon to use in the frontend, if any."""
return self.properties["icon"]

Expand Down
22 changes: 11 additions & 11 deletions homeassistant/components/ping/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,18 @@ def __init__(self, ip_address, dev_id, hass, config, privileged):

def ping(self):
"""Send an ICMP echo request and return True if success."""
pinger = subprocess.Popen(
with subprocess.Popen(
self._ping_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
)
try:
pinger.communicate(timeout=1 + PING_TIMEOUT)
return pinger.returncode == 0
except subprocess.TimeoutExpired:
kill_subprocess(pinger)
return False

except subprocess.CalledProcessError:
return False
) as pinger:
try:
pinger.communicate(timeout=1 + PING_TIMEOUT)
return pinger.returncode == 0
except subprocess.TimeoutExpired:
kill_subprocess(pinger)
return False

except subprocess.CalledProcessError:
return False

def update(self) -> bool:
"""Update device state by sending one or more ping messages."""
Expand Down
1 change: 1 addition & 0 deletions homeassistant/components/pushover/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ def send_message(self, message="", **kwargs):
if self._hass.config.is_allowed_path(data[ATTR_ATTACHMENT]):
# try to open it as a normal file.
try:
# pylint: disable=consider-using-with
file_handle = open(data[ATTR_ATTACHMENT], "rb")
# Replace the attachment identifier with file object.
image = file_handle
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/rpi_camera/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,8 @@ def delete_temp_file(*args):

# If no file path is defined, use a temporary file
if file_path is None:
temp_file = NamedTemporaryFile(suffix=".jpg", delete=False)
temp_file.close()
file_path = temp_file.name
with NamedTemporaryFile(suffix=".jpg", delete=False) as temp_file:
file_path = temp_file.name
setup_config[CONF_FILE_PATH] = file_path
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, delete_temp_file)

Expand Down
20 changes: 10 additions & 10 deletions homeassistant/components/seven_segments/image_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,14 @@ def process_image(self, image):
img = Image.open(stream)
img.save(self.filepath, "png")

ocr = subprocess.Popen(
with subprocess.Popen(
self._command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out = ocr.communicate()
if out[0] != b"":
self._state = out[0].strip().decode("utf-8")
else:
self._state = None
_LOGGER.warning(
"Unable to detect value: %s", out[1].strip().decode("utf-8")
)
) as ocr:
out = ocr.communicate()
if out[0] != b"":
self._state = out[0].strip().decode("utf-8")
else:
self._state = None
_LOGGER.warning(
"Unable to detect value: %s", out[1].strip().decode("utf-8")
)
2 changes: 1 addition & 1 deletion homeassistant/components/telegram_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def load_data(
_LOGGER.warning("Can't load data in %s after %s retries", url, retry_num)
elif filepath is not None:
if hass.config.is_allowed_path(filepath):
return open(filepath, "rb")
return open(filepath, "rb") # pylint: disable=consider-using-with

_LOGGER.warning("'%s' are not secure to load data from!", filepath)
else:
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/tradfri/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,7 @@ async def async_turn_on(self, **kwargs):
dimmer_command = None
if ATTR_BRIGHTNESS in kwargs:
brightness = kwargs[ATTR_BRIGHTNESS]
if brightness > 254:
brightness = 254
brightness = min(brightness, 254)
dimmer_data = {
ATTR_DIMMER: brightness,
ATTR_TRANSITION_TIME: transition_time,
Expand Down
3 changes: 2 additions & 1 deletion homeassistant/components/zeroconf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""Support for exposing Home Assistant via Zeroconf."""
from __future__ import annotations

from collections.abc import Iterable
from contextlib import suppress
import fnmatch
from functools import partial
import ipaddress
from ipaddress import ip_address
import logging
import socket
from typing import Any, Iterable, TypedDict, cast
from typing import Any, TypedDict, cast

from pyroute2 import IPRoute
import voluptuous as vol
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/zone/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from __future__ import annotations

import logging
from typing import Any, Dict, cast
from typing import Any, cast

import voluptuous as vol

Expand Down Expand Up @@ -163,7 +163,7 @@ class ZoneStorageCollection(collection.StorageCollection):

async def _process_create_data(self, data: dict) -> dict:
"""Validate the config is valid."""
return cast(Dict, self.CREATE_SCHEMA(data))
return cast(dict, self.CREATE_SCHEMA(data))

@callback
def _get_suggested_id(self, info: dict) -> str:
Expand Down Expand Up @@ -291,7 +291,7 @@ def from_yaml(cls, config: dict) -> Zone:
"""Return entity instance initialized from yaml storage."""
zone = cls(config)
zone.editable = False
zone._generate_attrs() # pylint:disable=protected-access
zone._generate_attrs()
return zone

@property
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from __future__ import annotations

import asyncio
from collections.abc import Awaitable, Collection, Iterable, Mapping
from collections.abc import Awaitable, Collection, Coroutine, Iterable, Mapping
import datetime
import enum
import functools
Expand All @@ -18,7 +18,7 @@
import threading
from time import monotonic
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional, TypeVar, cast
from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, cast

import attr
import voluptuous as vol
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/helpers/config_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ def verify(value: dict) -> dict:
for key in value.keys():
slug_validator(key)

return cast(Dict, schema(value))
return cast(dict, schema(value))

return verify

Expand Down
Loading