Fix PEP257 issues

This commit is contained in:
Fabian Affolter 2016-03-07 23:39:52 +01:00
parent 876978d64a
commit 4f536ac63d
9 changed files with 74 additions and 108 deletions

View File

@ -1,20 +1,17 @@
"""
Helper methods for components within Home Assistant.
"""
"""Helper methods for components within Home Assistant."""
import re
from homeassistant.const import CONF_PLATFORM
def validate_config(config, items, logger):
"""
Validates if all items are available in the configuration.
"""Validate if all items are available in the configuration.
config is the general dictionary with all the configurations.
items is a dict with per domain which attributes we require.
logger is the logger from the caller to log the errors to.
Returns True if all required items were found.
Return True if all required items were found.
"""
errors_found = False
for domain in items.keys():
@ -33,8 +30,8 @@ def validate_config(config, items, logger):
def config_per_platform(config, domain, logger):
"""
Generator to break a component config into different platforms.
"""Generator to break a component config into different platforms.
For example, will find 'switch', 'switch 2', 'switch 3', .. etc
"""
config_key = domain
@ -59,6 +56,6 @@ def config_per_platform(config, domain, logger):
def extract_domain_configs(config, domain):
""" Extract keys from config for given domain name. """
"""Extract keys from config for given domain name."""
pattern = re.compile(r'^{}(| .+)$'.format(domain))
return [key for key in config.keys() if pattern.match(key)]

View File

@ -1,8 +1,4 @@
"""
homeassistant.helpers.entity.
Provides ABC for entities in HA.
"""
"""An abstract class for entities in HA."""
import re
from collections import defaultdict
@ -49,15 +45,12 @@ class Entity(object):
"""ABC for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inherting this
# class. These may be used to customize the behavior of the entity.
@property
def should_poll(self):
"""
Return True if entity has to be polled for state.
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
@ -80,8 +73,7 @@ class Entity(object):
@property
def state_attributes(self):
"""
Return the state attributes.
"""Return the state attributes.
Implemented by component base class.
"""
@ -89,8 +81,7 @@ class Entity(object):
@property
def device_state_attributes(self):
"""
Return device specific state attributes.
"""Return device specific state attributes.
Implemented by platform classes.
"""
@ -140,8 +131,7 @@ class Entity(object):
hass = None
def update_ha_state(self, force_refresh=False):
"""
Update Home Assistant with current state of entity.
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
@ -176,10 +166,10 @@ class Entity(object):
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# overwrite properties that have been set in the config file
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# remove hidden property if false so it won't show up
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
@ -210,16 +200,17 @@ class Entity(object):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
@staticmethod
def overwrite_attribute(entity_id, attrs, vals):
"""
Overwrite any attribute of an entity.
"""Overwrite any attribute of an entity.
This function should receive a list of attributes and a
list of values. Set attribute to None to remove any overwritten
@ -236,7 +227,6 @@ class ToggleEntity(Entity):
"""ABC for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self):
"""Return the state."""
@ -244,7 +234,7 @@ class ToggleEntity(Entity):
@property
def is_on(self):
"""True if entity is on."""
"""Return True if entity is on."""
return False
def turn_on(self, **kwargs):

View File

@ -41,8 +41,7 @@ class EntityComponent(object):
self.scan_interval).add_entities
def setup(self, config):
"""
Set up a full entity component.
"""Set up a full entity component.
Loads the platforms from the config and will listen for supported
discovered platforms.
@ -63,8 +62,7 @@ class EntityComponent(object):
info))
def extract_from_service(self, service):
"""
Extract all known entities from a service call.
"""Extract all known entities from a service call.
Will return all entities if no entities specified in call.
Will return an empty list if entities specified but unknown.
@ -134,6 +132,7 @@ class EntityPlatform(object):
# pylint: disable=too-few-public-methods
def __init__(self, component, scan_interval):
"""Initalize the entity platform."""
self.component = component
self.scan_interval = scan_interval
self.platform_entities = []

View File

@ -1,6 +1,4 @@
"""
Helpers for listening to events
"""
"""Helpers for listening to events."""
import functools as ft
from datetime import timedelta
@ -11,8 +9,8 @@ from ..util import dt as dt_util
def track_state_change(hass, entity_ids, action, from_state=None,
to_state=None):
"""
Track specific state changes.
"""Track specific state changes.
entity_ids, from_state and to_state can be string or list.
Use list to match multiple.
@ -30,7 +28,7 @@ def track_state_change(hass, entity_ids, action, from_state=None,
@ft.wraps(action)
def state_change_listener(event):
""" The listener that listens for specific state changes. """
"""The listener that listens for specific state changes."""
if event.data['entity_id'] not in entity_ids:
return
@ -55,29 +53,25 @@ def track_state_change(hass, entity_ids, action, from_state=None,
def track_point_in_time(hass, action, point_in_time):
"""
Adds a listener that fires once after a spefic point in time.
"""
"""Add a listener that fires once after a spefic point in time."""
utc_point_in_time = dt_util.as_utc(point_in_time)
@ft.wraps(action)
def utc_converter(utc_now):
""" Converts passed in UTC now to local now. """
"""Convert passed in UTC now to local now."""
action(dt_util.as_local(utc_now))
return track_point_in_utc_time(hass, utc_converter, utc_point_in_time)
def track_point_in_utc_time(hass, action, point_in_time):
"""
Adds a listener that fires once after a specific point in UTC time.
"""
"""Add a listener that fires once after a specific point in UTC time."""
# Ensure point_in_time is UTC
point_in_time = dt_util.as_utc(point_in_time)
@ft.wraps(action)
def point_in_time_listener(event):
""" Listens for matching time_changed events. """
"""Listen for matching time_changed events."""
now = event.data[ATTR_NOW]
if now >= point_in_time and \
@ -100,14 +94,12 @@ def track_point_in_utc_time(hass, action, point_in_time):
def track_sunrise(hass, action, offset=None):
"""
Adds a listener that will fire a specified offset from sunrise daily.
"""
"""Add a listener that will fire a specified offset from sunrise daily."""
from homeassistant.components import sun
offset = offset or timedelta()
def next_rise():
""" Returns next sunrise. """
"""Return the next sunrise."""
next_time = sun.next_rising_utc(hass) + offset
while next_time < dt_util.utcnow():
@ -116,7 +108,7 @@ def track_sunrise(hass, action, offset=None):
return next_time
def sunrise_automation_listener(now):
""" Called when it's time for action. """
"""Called when it's time for action."""
track_point_in_utc_time(hass, sunrise_automation_listener, next_rise())
action()
@ -124,14 +116,12 @@ def track_sunrise(hass, action, offset=None):
def track_sunset(hass, action, offset=None):
"""
Adds a listener that will fire a specified offset from sunset daily.
"""
"""Add a listener that will fire a specified offset from sunset daily."""
from homeassistant.components import sun
offset = offset or timedelta()
def next_set():
""" Returns next sunrise. """
"""Return next sunrise."""
next_time = sun.next_setting_utc(hass) + offset
while next_time < dt_util.utcnow():
@ -140,7 +130,7 @@ def track_sunset(hass, action, offset=None):
return next_time
def sunset_automation_listener(now):
""" Called when it's time for action. """
"""Called when it's time for action."""
track_point_in_utc_time(hass, sunset_automation_listener, next_set())
action()
@ -150,13 +140,13 @@ def track_sunset(hass, action, offset=None):
# pylint: disable=too-many-arguments
def track_utc_time_change(hass, action, year=None, month=None, day=None,
hour=None, minute=None, second=None, local=False):
""" Adds a listener that will fire if time matches a pattern. """
"""Add a listener that will fire if time matches a pattern."""
# We do not have to wrap the function with time pattern matching logic
# if no pattern given
if all(val is None for val in (year, month, day, hour, minute, second)):
@ft.wraps(action)
def time_change_listener(event):
""" Fires every time event that comes in. """
"""Fire every time event that comes in."""
action(event.data[ATTR_NOW])
hass.bus.listen(EVENT_TIME_CHANGED, time_change_listener)
@ -168,7 +158,7 @@ def track_utc_time_change(hass, action, year=None, month=None, day=None,
@ft.wraps(action)
def pattern_time_change_listener(event):
""" Listens for matching time_changed events. """
"""Listen for matching time_changed events."""
now = event.data[ATTR_NOW]
if local:
@ -192,13 +182,13 @@ def track_utc_time_change(hass, action, year=None, month=None, day=None,
# pylint: disable=too-many-arguments
def track_time_change(hass, action, year=None, month=None, day=None,
hour=None, minute=None, second=None):
""" Adds a listener that will fire if UTC time matches a pattern. """
"""Add a listener that will fire if UTC time matches a pattern."""
track_utc_time_change(hass, action, year, month, day, hour, minute, second,
local=True)
def _process_match_param(parameter):
""" Wraps parameter in a tuple if it is not one and returns it. """
"""Wrap parameter in a tuple if it is not one and returns it."""
if parameter is None or parameter == MATCH_ALL:
return MATCH_ALL
elif isinstance(parameter, str) and parameter.startswith('/'):
@ -210,7 +200,7 @@ def _process_match_param(parameter):
def _matcher(subject, pattern):
""" Returns True if subject matches the pattern.
"""Return True if subject matches the pattern.
Pattern is either a tuple of allowed subjects or a `MATCH_ALL`.
"""

View File

@ -1,5 +1,4 @@
""" Event Decorators for custom components """
"""Event Decorators for custom components."""
import functools
from homeassistant.helpers import event
@ -8,10 +7,9 @@ HASS = None
def track_state_change(entity_ids, from_state=None, to_state=None):
""" Decorator factory to track state changes for entity id """
"""Decorator factory to track state changes for entity id."""
def track_state_change_decorator(action):
""" Decorator to track state changes """
"""Decorator to track state changes."""
event.track_state_change(HASS, entity_ids,
functools.partial(action, HASS),
from_state, to_state)
@ -21,10 +19,9 @@ def track_state_change(entity_ids, from_state=None, to_state=None):
def track_sunrise(offset=None):
""" Decorator factory to track sunrise events """
"""Decorator factory to track sunrise events."""
def track_sunrise_decorator(action):
""" Decorator to track sunrise events """
"""Decorator to track sunrise events."""
event.track_sunrise(HASS,
functools.partial(action, HASS),
offset)
@ -34,10 +31,9 @@ def track_sunrise(offset=None):
def track_sunset(offset=None):
""" Decorator factory to track sunset events """
"""Decorator factory to track sunset events."""
def track_sunset_decorator(action):
""" Decorator to track sunset events """
"""Decorator to track sunset events."""
event.track_sunset(HASS,
functools.partial(action, HASS),
offset)
@ -49,10 +45,9 @@ def track_sunset(offset=None):
# pylint: disable=too-many-arguments
def track_time_change(year=None, month=None, day=None, hour=None, minute=None,
second=None):
""" Decorator factory to track time changes """
"""Decorator factory to track time changes."""
def track_time_change_decorator(action):
""" Decorator to track time changes """
"""Decorator to track time changes."""
event.track_time_change(HASS,
functools.partial(action, HASS),
year, month, day, hour, minute, second)
@ -64,10 +59,9 @@ def track_time_change(year=None, month=None, day=None, hour=None, minute=None,
# pylint: disable=too-many-arguments
def track_utc_time_change(year=None, month=None, day=None, hour=None,
minute=None, second=None):
""" Decorator factory to track time changes """
"""Decorator factory to track time changes."""
def track_utc_time_change_decorator(action):
""" Decorator to track time changes """
"""Decorator to track time changes."""
event.track_utc_time_change(HASS,
functools.partial(action, HASS),
year, month, day, hour, minute, second)

View File

@ -16,10 +16,9 @@ _LOGGER = logging.getLogger(__name__)
def service(domain, service_name):
""" Decorator factory to register a service """
"""Decorator factory to register a service."""
def register_service_decorator(action):
""" Decorator to register a service """
"""Decorator to register a service."""
HASS.services.register(domain, service_name,
functools.partial(action, HASS))
return action
@ -60,8 +59,8 @@ def call_from_config(hass, config, blocking=False):
def extract_entity_ids(hass, service_call):
"""
Helper method to extract a list of entity ids from a service call.
"""Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
if not (service_call.data and ATTR_ENTITY_ID in service_call.data):

View File

@ -18,10 +18,10 @@ _LOGGER = logging.getLogger(__name__)
# pylint: disable=too-few-public-methods, attribute-defined-outside-init
class TrackStates(object):
"""
Records the time when the with-block is entered. Will add all states
that have changed since the start time to the return list when with-block
is exited.
"""Record the time when the with-block is entered.
Will add all states that have changed since the start time to the return
list when with-block is exited.
"""
def __init__(self, hass):
@ -100,7 +100,6 @@ def state_as_number(state):
Raises ValueError if this is not possible.
"""
if state.state in (STATE_ON, STATE_LOCKED, STATE_ABOVE_HORIZON,
STATE_OPEN):
return 1

View File

@ -1,16 +1,10 @@
"""
homeassistant.helpers.temperature
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Methods to help handle temperature in Home Assistant.
"""
"""Methods to help handle temperature in Home Assistant."""
import homeassistant.util.temperature as temp_util
from homeassistant.const import TEMP_CELCIUS
def convert(temperature, unit, to_unit):
""" Converts temperature to correct unit. """
"""Convert temperature to correct unit."""
if unit == to_unit or unit is None or to_unit is None:
return temperature
elif unit == TEMP_CELCIUS:

View File

@ -1,6 +1,4 @@
"""
Template helper methods for rendering strings with HA data.
"""
"""Template helper methods for rendering strings with HA data."""
# pylint: disable=too-few-public-methods
import json
import logging
@ -21,8 +19,8 @@ _SENTINEL = object()
def render_with_possible_json_value(hass, template, value,
error_value=_SENTINEL):
"""
Renders template with value exposed.
"""Render template with value exposed.
If valid JSON will expose value_json too.
"""
variables = {
@ -65,17 +63,22 @@ def render(hass, template, variables=None, **kwargs):
class AllStates(object):
"""Class to expose all HA states as attributes."""
def __init__(self, hass):
"""Initialize all states."""
self._hass = hass
def __getattr__(self, name):
"""Return the domain state."""
return DomainStates(self._hass, name)
def __iter__(self):
"""Return all states."""
return iter(sorted(self._hass.states.all(),
key=lambda state: state.entity_id))
def __call__(self, entity_id):
"""Return the states."""
state = self._hass.states.get(entity_id)
return STATE_UNKNOWN if state is None else state.state
@ -84,13 +87,16 @@ class DomainStates(object):
"""Class to expose a specific HA domain as attributes."""
def __init__(self, hass, domain):
"""Initialize the domain states."""
self._hass = hass
self._domain = domain
def __getattr__(self, name):
"""Return the states."""
return self._hass.states.get('{}.{}'.format(self._domain, name))
def __iter__(self):
"""Return the iteration over all the states."""
return iter(sorted(
(state for state in self._hass.states.all()
if state.domain == self._domain),
@ -101,7 +107,7 @@ class LocationMethods(object):
"""Class to expose distance helpers to templates."""
def __init__(self, hass):
"""Initialize distance helpers."""
"""Initialize the distance helpers."""
self._hass = hass
def closest(self, *args):
@ -118,7 +124,6 @@ class LocationMethods(object):
closest('zone.school', 'group.children')
closest(states.zone.school, 'group.children')
"""
if len(args) == 1:
latitude = self._hass.config.latitude
longitude = self._hass.config.longitude
@ -250,8 +255,7 @@ def forgiving_float(value):
class TemplateEnvironment(ImmutableSandboxedEnvironment):
"""Home Assistant template environment."""
"""The Home Assistant template environment."""
def is_safe_callable(self, obj):
"""Test if callback is safe."""
return isinstance(obj, AllStates) or super().is_safe_callable(obj)