Skip to content

Commit

Permalink
Fix PEP257 issues
Browse files Browse the repository at this point in the history
  • Loading branch information
fabaff committed Mar 7, 2016
1 parent 876978d commit 4f536ac
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 108 deletions.
15 changes: 6 additions & 9 deletions homeassistant/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -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():
Expand All @@ -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
Expand All @@ -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)]
32 changes: 11 additions & 21 deletions homeassistant/helpers/entity.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.
"""
Expand All @@ -80,17 +73,15 @@ def state(self):

@property
def state_attributes(self):
"""
Return the state attributes.
"""Return the state attributes.
Implemented by component base class.
"""
return None

@property
def device_state_attributes(self):
"""
Return device specific state attributes.
"""Return device specific state attributes.
Implemented by platform classes.
"""
Expand Down Expand Up @@ -140,8 +131,7 @@ def update(self):
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.
"""
Expand Down Expand Up @@ -176,10 +166,10 @@ def update_ha_state(self, force_refresh=False):
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)

Expand Down Expand Up @@ -210,16 +200,17 @@ def _attr_setter(self, name, typ, attr, attrs):
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
Expand All @@ -236,15 +227,14 @@ 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."""
return STATE_ON if self.is_on else STATE_OFF

@property
def is_on(self):
"""True if entity is on."""
"""Return True if entity is on."""
return False

def turn_on(self, **kwargs):
Expand Down
7 changes: 3 additions & 4 deletions homeassistant/helpers/entity_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ def __init__(self, logger, domain, hass,
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.
Expand All @@ -63,8 +62,7 @@ def setup(self, config):
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.
Expand Down Expand Up @@ -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 = []
Expand Down
50 changes: 20 additions & 30 deletions homeassistant/helpers/event.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Helpers for listening to events
"""
"""Helpers for listening to events."""
import functools as ft
from datetime import timedelta

Expand All @@ -11,8 +9,8 @@

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.
Expand All @@ -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

Expand All @@ -55,29 +53,25 @@ def state_change_listener(event):


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 \
Expand All @@ -100,14 +94,12 @@ def point_in_time_listener(event):


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():
Expand All @@ -116,22 +108,20 @@ def next_rise():
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()

track_point_in_utc_time(hass, sunrise_automation_listener, next_rise())


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():
Expand All @@ -140,7 +130,7 @@ def next_set():
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()

Expand All @@ -150,13 +140,13 @@ def sunset_automation_listener(now):
# 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)
Expand All @@ -168,7 +158,7 @@ def time_change_listener(event):

@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:
Expand All @@ -192,13 +182,13 @@ def pattern_time_change_listener(event):
# 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('/'):
Expand All @@ -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`.
"""
Expand Down
Loading

0 comments on commit 4f536ac

Please sign in to comment.