Merge pull request #683 from balloob/pylint-15-fixes

PyLint 1.5 fixes
pull/671/head
Paulus Schoutsen 2015-11-29 14:11:35 -08:00
commit 35f1810c74
37 changed files with 140 additions and 125 deletions

View File

@ -82,7 +82,7 @@ def _in_range(value, range_start, range_end):
try:
value = float(value)
except ValueError:
_LOGGER.warn("Missing value in numeric check")
_LOGGER.warning("Missing value in numeric check")
return False
if range_start is not None and range_end is not None:

View File

@ -46,6 +46,7 @@ def trigger(hass, config, action):
from_match = _in_zone(hass, zone_entity_id, from_s) if from_s else None
to_match = _in_zone(hass, zone_entity_id, to_s)
# pylint: disable=too-many-boolean-expressions
if event == EVENT_ENTER and not from_match and to_match or \
event == EVENT_LEAVE and from_match and not to_match:
action()

View File

@ -6,9 +6,10 @@ The arest sensor will consume an exposed aREST API of a device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.arest/
"""
import logging
import requests
from datetime import timedelta
import logging
import requests
from homeassistant.util import Throttle
from homeassistant.components.binary_sensor import BinarySensorDevice

View File

@ -7,19 +7,20 @@ Component to interface with various cameras.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import requests
import logging
import time
import re
import time
import requests
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.const import (
ATTR_ENTITY_PICTURE,
HTTP_NOT_FOUND,
ATTR_ENTITY_ID,
)
from homeassistant.helpers.entity_component import EntityComponent
DOMAIN = 'camera'
DEPENDENCIES = ['http']

View File

@ -7,11 +7,12 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.foscam/
"""
import logging
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN
from homeassistant.components.camera import Camera
import requests
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN, Camera
_LOGGER = logging.getLogger(__name__)

View File

@ -7,11 +7,12 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.generic/
"""
import logging
from requests.auth import HTTPBasicAuth
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN
from homeassistant.components.camera import Camera
import requests
from requests.auth import HTTPBasicAuth
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN, Camera
_LOGGER = logging.getLogger(__name__)

View File

@ -6,13 +6,14 @@ Support for IP Cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.mjpeg/
"""
import logging
from requests.auth import HTTPBasicAuth
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN
from homeassistant.components.camera import Camera
import requests
from contextlib import closing
import logging
import requests
from requests.auth import HTTPBasicAuth
from homeassistant.helpers import validate_config
from homeassistant.components.camera import DOMAIN, Camera
_LOGGER = logging.getLogger(__name__)

View File

@ -26,14 +26,15 @@ ecobee:
"""
from datetime import timedelta
import logging
import os
from homeassistant.loader import get_component
from homeassistant import bootstrap
from homeassistant.util import Throttle
from homeassistant.const import (
EVENT_PLATFORM_DISCOVERED, ATTR_SERVICE, ATTR_DISCOVERED, CONF_API_KEY)
from datetime import timedelta
import logging
import os
DOMAIN = "ecobee"
DISCOVER_THERMOSTAT = "ecobee.thermostat"

View File

@ -6,12 +6,13 @@ Support for Z-Wave lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.zwave/
"""
# Because we do not compile openzwave on CI
# pylint: disable=import-error
import homeassistant.components.zwave as zwave
from threading import Timer
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.components.light import (Light, ATTR_BRIGHTNESS)
from threading import Timer
import homeassistant.components.zwave as zwave
def setup_platform(hass, config, add_devices, discovery_info=None):

View File

@ -49,7 +49,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.info(
'Device %s accessible and ready for control', device_id)
else:
_LOGGER.warn(
_LOGGER.warning(
'Device %s is not registered with firetv-server', device_id)
except requests.exceptions.RequestException:
_LOGGER.error('Could not connect to firetv-server at %s', host)

View File

@ -8,6 +8,8 @@ https://home-assistant.io/components/media_player.itunes/
"""
import logging
import requests
from homeassistant.components.media_player import (
MediaPlayerDevice, MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, SUPPORT_PAUSE,
SUPPORT_SEEK, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_MUTE,
@ -17,8 +19,6 @@ from homeassistant.components.media_player import (
from homeassistant.const import (
STATE_IDLE, STATE_PLAYING, STATE_PAUSED, STATE_OFF, STATE_ON)
import requests
_LOGGER = logging.getLogger(__name__)
SUPPORT_ITUNES = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \

View File

@ -15,11 +15,6 @@ from homeassistant.components.media_player import (
from homeassistant.const import (
STATE_IDLE, STATE_PLAYING, STATE_PAUSED, STATE_OFF)
try:
import jsonrpc_requests
except ImportError:
jsonrpc_requests = None
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['jsonrpc-requests==0.1']
@ -31,11 +26,6 @@ SUPPORT_KODI = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the kodi platform. """
global jsonrpc_requests # pylint: disable=invalid-name
if jsonrpc_requests is None:
import jsonrpc_requests as jsonrpc_requests_
jsonrpc_requests = jsonrpc_requests_
add_devices([
KodiDevice(
config.get('name', 'Kodi'),
@ -60,6 +50,7 @@ class KodiDevice(MediaPlayerDevice):
# pylint: disable=too-many-public-methods
def __init__(self, name, url, auth=None):
import jsonrpc_requests
self._name = name
self._url = url
self._server = jsonrpc_requests.Server(url, auth=auth)
@ -77,6 +68,7 @@ class KodiDevice(MediaPlayerDevice):
def _get_players(self):
""" Returns the active player objects or None """
import jsonrpc_requests
try:
return self._server.Player.GetActivePlayers()
except jsonrpc_requests.jsonrpc.TransportError:

View File

@ -8,14 +8,14 @@ https://home-assistant.io/components/notify.xmpp/
"""
import logging
_LOGGER = logging.getLogger(__name__)
from homeassistant.helpers import validate_config
from homeassistant.components.notify import (
DOMAIN, ATTR_TITLE, BaseNotificationService)
REQUIREMENTS = ['sleekxmpp==1.3.1', 'dnspython3==1.12.0']
_LOGGER = logging.getLogger(__name__)
def get_service(hass, config):
""" Get the Jabber (XMPP) notification service. """

View File

@ -73,7 +73,7 @@ def row_to_state(row):
def row_to_event(row):
""" Convert a databse row to an event. """
try:
return Event(row[1], json.loads(row[2]), EventOrigin[row[3].lower()],
return Event(row[1], json.loads(row[2]), EventOrigin(row[3]),
date_util.utc_from_timestamp(row[5]))
except ValueError:
# When json.loads fails

View File

@ -9,7 +9,6 @@ https://home-assistant.io/components/script/
"""
import logging
from datetime import timedelta
import homeassistant.util.dt as date_util
from itertools import islice
import threading
@ -17,6 +16,7 @@ from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.event import track_point_in_utc_time
from homeassistant.util import slugify, split_entity_id
import homeassistant.util.dt as date_util
from homeassistant.const import (
ATTR_ENTITY_ID, EVENT_TIME_CHANGED, STATE_ON, SERVICE_TURN_ON,
SERVICE_TURN_OFF)
@ -73,12 +73,12 @@ def setup(hass, config):
for object_id, cfg in config[DOMAIN].items():
if object_id != slugify(object_id):
_LOGGER.warn("Found invalid key for script: %s. Use %s instead.",
object_id, slugify(object_id))
_LOGGER.warning("Found invalid key for script: %s. Use %s instead",
object_id, slugify(object_id))
continue
if not isinstance(cfg.get(CONF_SEQUENCE), list):
_LOGGER.warn("Key 'sequence' for script %s should be a list",
object_id)
_LOGGER.warning("Key 'sequence' for script %s should be a list",
object_id)
continue
alias = cfg.get(CONF_ALIAS, object_id)
script = Script(hass, object_id, alias, cfg[CONF_SEQUENCE])

View File

@ -6,13 +6,14 @@ The arest sensor will consume an exposed aREST API of a device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.arest/
"""
import logging
import requests
from datetime import timedelta
import logging
import requests
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)

View File

@ -25,10 +25,11 @@ ecobee:
hold_temp: True
"""
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.components import ecobee
from homeassistant.const import TEMP_FAHRENHEIT
import logging
DEPENDENCIES = ['ecobee']

View File

@ -9,17 +9,11 @@ https://home-assistant.io/components/sensor.forecast/
import logging
from datetime import timedelta
REQUIREMENTS = ['python-forecastio==1.3.3']
try:
import forecastio
except ImportError:
forecastio = None
from homeassistant.util import Throttle
from homeassistant.const import (CONF_API_KEY, TEMP_CELCIUS)
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['python-forecastio==1.3.3']
_LOGGER = logging.getLogger(__name__)
# Sensor types are defined like so:
@ -53,11 +47,7 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=120)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the Forecast.io sensor. """
global forecastio # pylint: disable=invalid-name
if forecastio is None:
import forecastio as forecastio_
forecastio = forecastio_
import forecastio
if None in (hass.config.latitude, hass.config.longitude):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
@ -141,6 +131,7 @@ class ForeCastSensor(Entity):
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from Forecast.io and updates the states. """
import forecastio
self.forecast_client.update()
data = self.forecast_client.data
@ -209,6 +200,7 @@ class ForeCastData(object):
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Gets the latest data from Forecast.io. """
import forecastio
forecast = forecastio.load_forecast(self._api_key,
self.latitude,

View File

@ -6,9 +6,10 @@ Gathers system information of hosts which running glances.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.glances/
"""
import logging
import requests
from datetime import timedelta
import logging
import requests
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity

View File

@ -6,10 +6,11 @@ The rest sensor will consume JSON responses sent by an exposed REST API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rest/
"""
import logging
import requests
from json import loads
from datetime import timedelta
from json import loads
import logging
import requests
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity

View File

@ -6,13 +6,10 @@ Allows to configure a binary state sensor using RPi GPIO.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rpi_gpio/
"""
# pylint: disable=import-error
import logging
from homeassistant.helpers.entity import Entity
try:
import RPi.GPIO as GPIO
except ImportError:
GPIO = None
from homeassistant.const import (DEVICE_DEFAULT_NAME,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP)
@ -29,10 +26,7 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Raspberry PI GPIO ports. """
if GPIO is None:
_LOGGER.error('RPi.GPIO not available. rpi_gpio ports ignored.')
return
# pylint: disable=no-member
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
sensors = []
@ -65,6 +59,7 @@ class RPiGPIOSensor(Entity):
def __init__(self, port_name, port_num, pull_mode,
value_high, value_low, bouncetime):
# pylint: disable=no-member
import RPi.GPIO as GPIO
self._name = port_name or DEVICE_DEFAULT_NAME
self._port = port_num
self._pull = GPIO.PUD_DOWN if pull_mode == "DOWN" else GPIO.PUD_UP

View File

@ -6,12 +6,11 @@ Monitors SABnzbd NZB client API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.sabnzbd/
"""
from homeassistant.util import Throttle
from datetime import timedelta
import logging
from homeassistant.helpers.entity import Entity
import logging
from homeassistant.util import Throttle
REQUIREMENTS = ['https://github.com/jamespcole/home-assistant-nzb-clients/'
'archive/616cad59154092599278661af17e2a9f2cf5e2a9.zip'

View File

@ -6,14 +6,13 @@ Monitors Transmission BitTorrent client API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.transmission/
"""
from homeassistant.util import Throttle
from datetime import timedelta
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.helpers.entity import Entity
import logging
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.util import Throttle
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['transmissionrpc==0.11']
SENSOR_TYPES = {
'current_status': ['Status', ''],

View File

@ -95,7 +95,7 @@ class VeraSensor(Entity):
@property
def state_attributes(self):
attr = super().state_attributes
attr = {}
if self.vera_device.has_battery:
attr[ATTR_BATTERY_LEVEL] = self.vera_device.battery_level + '%'

View File

@ -6,9 +6,11 @@ Interfaces with Z-Wave sensors.
For more details about this platform, please refer to the documentation
at https://home-assistant.io/components/zwave/
"""
# Because we do not compile openzwave on CI
# pylint: disable=import-error
from homeassistant.helpers.event import track_point_in_time
import datetime
from homeassistant.helpers.event import track_point_in_time
import homeassistant.util.dt as dt_util
import homeassistant.components.zwave as zwave
from homeassistant.helpers.entity import Entity

View File

@ -6,11 +6,12 @@ Support turning on/off motion detection on Hikvision cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.hikvision/
"""
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
import logging
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import (STATE_ON, STATE_OFF,
CONF_HOST, CONF_USERNAME, CONF_PASSWORD)
_LOGGING = logging.getLogger(__name__)
REQUIREMENTS = ['hikvision==0.4']
# pylint: disable=too-many-arguments

View File

@ -91,12 +91,9 @@ class MyStromSwitch(SwitchDevice):
try:
request = requests.get('{}/report'.format(self._resource),
timeout=10)
if request.json()['relay'] is True:
self._state = True
else:
self._state = False
self.consumption = request.json()['power']
data = request.json()
self._state = bool(data['relay'])
self.consumption = data['power']
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device '%s'. Is device offline?",
self._resource)

View File

@ -6,12 +6,12 @@ Enable or disable Transmission BitTorrent client Turtle Mode.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.transmission/
"""
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.helpers.entity import ToggleEntity
import logging
from homeassistant.const import (CONF_HOST, CONF_USERNAME, CONF_PASSWORD,
STATE_ON, STATE_OFF)
from homeassistant.helpers.entity import ToggleEntity
_LOGGING = logging.getLogger(__name__)
REQUIREMENTS = ['transmissionrpc==0.11']

View File

@ -4,8 +4,8 @@ homeassistant.components.switch.zwave
Zwave platform that handles simple binary switches.
"""
# Because we do not compile openzwave on CI
# pylint: disable=import-error
import homeassistant.components.zwave as zwave
from homeassistant.components.switch import SwitchDevice

View File

@ -25,11 +25,12 @@ ecobee:
hold_temp: True
"""
import logging
from homeassistant.components import ecobee
from homeassistant.components.thermostat import (ThermostatDevice, STATE_COOL,
STATE_IDLE, STATE_HEAT)
from homeassistant.const import (TEMP_FAHRENHEIT, STATE_ON, STATE_OFF)
from homeassistant.components import ecobee
import logging
DEPENDENCIES = ['ecobee']

View File

@ -47,10 +47,10 @@ def get_newest_version():
return req.json()['info']['version']
except requests.RequestException:
_LOGGER.exception('Could not contact PyPI to check for updates')
return
return None
except ValueError:
_LOGGER.exception('Received invalid response from PyPI')
return
return None
except KeyError:
_LOGGER.exception('Response from PyPI did not include version')
return
return None

View File

@ -67,7 +67,7 @@ def create_default_config(config_dir, detect_location=True):
Returns path to new config file if success, None if failed. """
config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
info = {attr: default for attr, default, *_ in DEFAULT_CONFIG}
info = {attr: default for attr, default, _, _ in DEFAULT_CONFIG}
location_info = detect_location and loc_util.detect_location_info()

View File

@ -124,6 +124,7 @@ def track_utc_time_change(hass, action, year=None, month=None, day=None,
mat = _matcher
# pylint: disable=too-many-boolean-expressions
if mat(now.year, year) and \
mat(now.month, month) and \
mat(now.day, day) and \

View File

@ -1,12 +1,13 @@
"""Helpers to install PyPi packages."""
import logging
import os
import pkg_resources
import subprocess
import sys
import threading
from urllib.parse import urlparse
import pkg_resources
_LOGGER = logging.getLogger(__name__)
INSTALL_LOCK = threading.Lock()
@ -27,7 +28,7 @@ def install_package(package, upgrade=True, target=None):
args += ['--target', os.path.abspath(target)]
try:
return 0 == subprocess.call(args)
return subprocess.call(args) == 0
except subprocess.SubprocessError:
_LOGGER.exception('Unable to install pacakge %s', package)
return False
@ -50,4 +51,5 @@ def check_package_exists(package, lib_dir):
return True
# Check packages from global + virtual environment
# pylint: disable=not-an-iterable
return any(dist in req for dist in pkg_resources.working_set)

View File

@ -9,6 +9,7 @@ reports=no
# abstract-class-not-used - is flaky, should not show up but does
# unused-argument - generic callbacks and setup methods create a lot of warnings
# global-statement - used for the on-demand requirement installation
# redefined-variable-type - this is Python, we're duck typing!
disable=
locally-disabled,
duplicate-code,
@ -16,7 +17,8 @@ disable=
abstract-class-little-used,
abstract-class-not-used,
unused-argument,
global-statement
global-statement,
redefined-variable-type
[EXCEPTIONS]
overgeneral-exceptions=Exception,HomeAssistantError

View File

@ -170,4 +170,3 @@ https://github.com/persandstrom/python-verisure/archive/9873c4527f01b1ba1f72ae60
# homeassistant.components.zwave
pydispatcher==2.0.5

View File

@ -16,6 +16,7 @@ COMMENT_REQUIREMENTS = [
def explore_module(package, explore_children):
""" Explore the modules. """
module = importlib.import_module(package)
found = []
@ -33,10 +34,10 @@ def explore_module(package, explore_children):
def core_requirements():
""" Gather core requirements out of setup.py. """
with open('setup.py') as inp:
reqs_raw = re.search(
r'REQUIRES = \[(.*?)\]', inp.read(), re.S).group(1)
return re.findall(r"'(.*?)'", reqs_raw)
@ -45,14 +46,13 @@ def comment_requirement(req):
return any(ign in req for ign in COMMENT_REQUIREMENTS)
def main():
if not os.path.isfile('requirements_all.txt'):
print('Run this from HA root dir')
return
def gather_modules():
""" Collect the information and construct the output. """
reqs = OrderedDict()
errors = []
output = []
for package in sorted(explore_module('homeassistant.components', True)):
try:
module = importlib.import_module(package)
@ -69,22 +69,43 @@ def main():
if errors:
print("Found errors")
print('\n'.join(errors))
return
print('# Home Assistant core')
print('\n'.join(core_requirements()))
print()
return None
output.append('# Home Assistant core')
output.append('\n')
output.append('\n'.join(core_requirements()))
output.append('\n')
for pkg, requirements in reqs.items():
for req in sorted(requirements,
key=lambda name: (len(name.split('.')), name)):
print('#', req)
output.append('\n# {}'.format(req))
if comment_requirement(pkg):
print('#', pkg)
output.append('\n# {}\n'.format(pkg))
else:
print(pkg)
print()
output.append('\n{}\n'.format(pkg))
return ''.join(output)
def write_file(data):
""" Writes the modules to the requirements_all.txt. """
with open('requirements_all.txt', 'w+') as req_file:
req_file.write(data)
def main():
""" Main """
if not os.path.isfile('requirements_all.txt'):
print('Run this from HA root dir')
return
data = gather_modules()
if data is None:
return
write_file(data)
if __name__ == '__main__':
main()