RFC: Use bind_hass for helpers (#9745)

* Add Helpers bind_hass functionality

* Update other helpers
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2017-10-08 08:17:54 -07:00
1 parent e19e9a1f2b
commit ca54bbfcc9
16 files changed
+108 -25

No files matched your search

+24 -8
View File
@@ -4,7 +4,7 @@ Provides methods for loading Home Assistant components.
This module has quite some complex parts. I have tried to add as much
documentation as possible to keep it understandable.
Components are loaded by calling get_component('switch') from your code.
Components can be accessed via hass.components.switch from your code.
If you want to retrieve a platform that is part of a component, you should
call get_component('switch.your_platform'). In both cases the config directory
is checked to see if it contains a user provided version. If not available it
@@ -183,22 +183,38 @@ class Components:
component = get_component(comp_name)
if component is None:
raise ImportError('Unable to load {}'.format(comp_name))
wrapped = ComponentWrapper(self._hass, component)
wrapped = ModuleWrapper(self._hass, component)
setattr(self, comp_name, wrapped)
return wrapped
class ComponentWrapper:
"""Class to wrap a component and auto fill in hass argument."""
class Helpers:
"""Helper to load helpers."""
def __init__(self, hass, component):
"""Initialize the component wrapper."""
def __init__(self, hass):
"""Initialize the Helpers class."""
self._hass = hass
self._component = component
def __getattr__(self, helper_name):
"""Fetch a helper."""
helper = importlib.import_module(
'homeassistant.helpers.{}'.format(helper_name))
wrapped = ModuleWrapper(self._hass, helper)
setattr(self, helper_name, wrapped)
return wrapped
class ModuleWrapper:
"""Class to wrap a Python module and auto fill in hass argument."""
def __init__(self, hass, module):
"""Initialize the module wrapper."""
self._hass = hass
self._module = module
def __getattr__(self, attr):
"""Fetch an attribute."""
value = getattr(self._component, attr)
value = getattr(self._module, attr)
if hasattr(value, '__bind_hass'):
value = ft.partial(value, self._hass)