custom-components / pyscript

Pyscript adds rich Python scripting to HASS
Apache License 2.0
894 stars 47 forks source link

Expose home assistant jinja template functions #568

Open austinche opened 10 months ago

austinche commented 10 months ago

One thing missing from pyscript compared with regular home assistant scripts and automations is access to the capabilities provided by the jinja template extensions such as working with areas and devices. As described in #251, it is possible to provide pyscript access to the template functions. The following code exposes all functions that take the hass object (https://www.home-assistant.io/docs/configuration/templating/).

With the following in modules/template.py and after import template you can call any of these functions like template.device_entities(device_id).

import homeassistant.helpers.template as template

hass_template_functions = [
    'device_entities', 
    'device_attr', 
    'is_device_attr', 
    'config_entry_id', 
    'device_id', 
    'areas', 
    'area_id',
    'area_name',
    'area_entities',
    'area_devices', 
    'integration_entities',
    'expand',
    'closest',
    'distance',
    'is_hidden_entity',
    'is_state',
    'is_state_attr',
    'state_attr',
    'has_value',
    'utcnow',
    'now',
    'relative_time',
    'today_at',
]

def hass_template_wrap(fn_name):
    def wrap(*args, **kwargs):
        return getattr(template, fn_name)(hass, *args, **kwargs)
    return wrap

for fn in hass_template_functions:
    globals()[fn] = hass_template_wrap(fn)

This is pretty generic, easily maintainable, and feels like it should be part of pyscript core. It would eliminate a large part of the need to enable access to hass as a global variable or allowing all imports and makes it more straightforward to port any existing automation to pyscript.

ALERTua commented 10 months ago

Maybe you could create a few usage examples and maybe create a pull request to support templating?