Pylint cleanups (#35409)

* Avoid some outer name redefinitions

* Remove unneeded directives

* Narrow directive scope

* Don't disable redefined-variable-type
This commit is contained in:
Ville Skyttä 2020-05-09 14:08:40 +03:00 committed by GitHub
parent c37100299a
commit b4404b071f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 26 additions and 35 deletions

View file

@ -61,8 +61,7 @@ class CommandLineAuthProvider(AuthProvider):
"""Validate a username and password."""
env = {"username": username, "password": password}
try:
# pylint: disable=no-member
process = await asyncio.subprocess.create_subprocess_exec(
process = await asyncio.subprocess.create_subprocess_exec( # pylint: disable=no-member
self.config[CONF_COMMAND],
*self.config[CONF_ARGS],
env=env,

View file

@ -138,8 +138,9 @@ class Data:
if not bcrypt.checkpw(password.encode(), user_hash):
raise InvalidAuth
# pylint: disable=no-self-use
def hash_password(self, password: str, for_storage: bool = False) -> bytes:
def hash_password( # pylint: disable=no-self-use
self, password: str, for_storage: bool = False
) -> bytes:
"""Encode a password."""
hashed: bytes = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

View file

@ -1,5 +1,4 @@
"""Module to help with parsing and generating configuration files."""
# pylint: disable=no-name-in-module
from collections import OrderedDict
from distutils.version import LooseVersion # pylint: disable=import-error
import logging
@ -183,9 +182,9 @@ CORE_CONFIG_SCHEMA = CUSTOMIZE_CONFIG_SCHEMA.extend(
CONF_TIME_ZONE: cv.time_zone,
vol.Optional(CONF_INTERNAL_URL): cv.url,
vol.Optional(CONF_EXTERNAL_URL): cv.url,
vol.Optional(CONF_WHITELIST_EXTERNAL_DIRS):
# pylint: disable=no-value-for-parameter
vol.All(cv.ensure_list, [vol.IsDir()]),
vol.Optional(CONF_WHITELIST_EXTERNAL_DIRS): vol.All(
cv.ensure_list, [vol.IsDir()] # pylint: disable=no-value-for-parameter
),
vol.Optional(CONF_PACKAGES, default={}): PACKAGES_CONFIG_SCHEMA,
vol.Optional(CONF_AUTH_PROVIDERS): vol.All(
cv.ensure_list,

View file

@ -851,8 +851,7 @@ class ConfigFlow(data_entry_flow.FlowHandler):
if progress["context"].get("unique_id") == unique_id:
raise data_entry_flow.AbortFlow("already_in_progress")
# pylint: disable=no-member
self.context["unique_id"] = unique_id
self.context["unique_id"] = unique_id # pylint: disable=no-member
for entry in self._async_current_entries():
if entry.unique_id == unique_id:

View file

@ -26,7 +26,6 @@ from typing import (
)
# Typing imports that create a circular dependency
# pylint: disable=unused-import
if TYPE_CHECKING:
from homeassistant.core import HomeAssistant

View file

@ -24,11 +24,9 @@ import slugify as unicode_slug
from .dt import as_local, utcnow
# pylint: disable=invalid-name
T = TypeVar("T")
U = TypeVar("U")
ENUM_T = TypeVar("ENUM_T", bound=enum.Enum)
# pylint: enable=invalid-name
U = TypeVar("U") # pylint: disable=invalid-name
ENUM_T = TypeVar("ENUM_T", bound=enum.Enum) # pylint: disable=invalid-name
RE_SANITIZE_FILENAME = re.compile(r"(~|\.\.|/|\\)")
RE_SANITIZE_PATH = re.compile(r"(~|\.(\.)+)")
@ -214,7 +212,6 @@ class Throttle:
If we cannot acquire the lock, it is running so return None.
"""
# pylint: disable=protected-access
if hasattr(method, "__self__"):
host = getattr(method, "__self__")
elif is_func:
@ -222,12 +219,14 @@ class Throttle:
else:
host = args[0] if args else wrapper
# pylint: disable=protected-access # to _throttle
if not hasattr(host, "_throttle"):
host._throttle = {}
if id(self) not in host._throttle:
host._throttle[id(self)] = [threading.Lock(), None]
throttle = host._throttle[id(self)]
# pylint: enable=protected-access
if not throttle[0].acquire(False):
return throttled_value()

View file

@ -244,9 +244,11 @@ def parse_time_expression(parameter: Any, min_value: int, max_value: int) -> Lis
return res
# pylint: disable=redefined-outer-name
def find_next_time_expression_time(
now: dt.datetime, seconds: List[int], minutes: List[int], hours: List[int]
now: dt.datetime, # pylint: disable=redefined-outer-name
seconds: List[int],
minutes: List[int],
hours: List[int],
) -> dt.datetime:
"""Find the next datetime from now for which the time expression matches.

View file

@ -56,7 +56,6 @@ def save_json(
try:
json_data = json.dumps(data, sort_keys=True, indent=4, cls=encoder)
except TypeError:
# pylint: disable=no-member
msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}"
_LOGGER.error(msg)
raise SerializationError(msg)

View file

@ -80,7 +80,6 @@ def distance(
# Author: https://github.com/maurycyp
# Source: https://github.com/maurycyp/vincenty
# License: https://github.com/maurycyp/vincenty/blob/master/LICENSE
# pylint: disable=invalid-name
def vincenty(
point1: Tuple[float, float], point2: Tuple[float, float], miles: bool = False
) -> Optional[float]:
@ -96,6 +95,7 @@ def vincenty(
if point1[0] == point2[0] and point1[1] == point2[1]:
return 0.0
# pylint: disable=invalid-name
U1 = math.atan((1 - FLATTENING) * math.tan(math.radians(point1[0])))
U2 = math.atan((1 - FLATTENING) * math.tan(math.radians(point2[0])))
L = math.radians(point2[1] - point1[1])

View file

@ -24,7 +24,6 @@ class HideSensitiveDataFilter(logging.Filter):
return True
# pylint: disable=invalid-name
class AsyncHandler:
"""Logging handler wrapper to add an async layer."""
@ -36,6 +35,7 @@ class AsyncHandler:
self._thread = threading.Thread(target=self._process)
# Delegate from handler
# pylint: disable=invalid-name
self.setLevel = handler.setLevel
self.setFormatter = handler.setFormatter
self.addFilter = handler.addFilter
@ -94,7 +94,7 @@ class AsyncHandler:
except asyncio.CancelledError:
self.handler.close()
def createLock(self) -> None:
def createLock(self) -> None: # pylint: disable=invalid-name
"""Ignore lock stuff."""
def acquire(self) -> None:

View file

@ -24,29 +24,28 @@ def save_yaml(path: str, data: dict) -> None:
# From: https://gist.github.com/miracle2k/3184458
# pylint: disable=redefined-outer-name
def represent_odict( # type: ignore
dump, tag, mapping, flow_style=None
dumper, tag, mapping, flow_style=None
) -> yaml.MappingNode:
"""Like BaseRepresenter.represent_mapping but does not issue the sort()."""
value: list = []
node = yaml.MappingNode(tag, value, flow_style=flow_style)
if dump.alias_key is not None:
dump.represented_objects[dump.alias_key] = node
if dumper.alias_key is not None:
dumper.represented_objects[dumper.alias_key] = node
best_style = True
if hasattr(mapping, "items"):
mapping = mapping.items()
for item_key, item_value in mapping:
node_key = dump.represent_data(item_key)
node_value = dump.represent_data(item_value)
node_key = dumper.represent_data(item_key)
node_value = dumper.represent_data(item_value)
if not (isinstance(node_key, yaml.ScalarNode) and not node_key.style):
best_style = False
if not (isinstance(node_value, yaml.ScalarNode) and not node_value.style):
best_style = False
value.append((node_key, node_value))
if flow_style is None:
if dump.default_flow_style is not None:
node.flow_style = dump.default_flow_style
if dumper.default_flow_style is not None:
node.flow_style = dumper.default_flow_style
else:
node.flow_style = best_style
return node

View file

@ -88,9 +88,6 @@ def _add_reference(
...
# pylint: enable=pointless-statement
def _add_reference( # type: ignore
obj, loader: SafeLineLoader, node: yaml.nodes.Node
):

View file

@ -18,7 +18,6 @@ good-names=id,i,j,k,ex,Run,_,fp,T
# cyclic-import - doesn't test if both import on load
# abstract-class-little-used - prevents from setting right foundation
# unused-argument - generic callbacks and setup methods create a lot of warnings
# redefined-variable-type - this is Python, we're duck typing!
# too-many-* - are not enforced for the sake of readability
# too-few-* - same as too-many-*
# abstract-method - with intro of async there are always methods missing
@ -34,7 +33,6 @@ disable=
inconsistent-return-statements,
locally-disabled,
not-context-manager,
redefined-variable-type,
too-few-public-methods,
too-many-ancestors,
too-many-arguments,