Comments (4)
One reason (and maybe the only reason) why the yaml
package won't work with pyscript
is that the callback functions you register via calls like yaml.add_constructor()
or yaml.add_representer()
need to be regular functions. However, all pyscript
functions are async
, so they won't work as callbacks.
The solution as you discovered is @pyscript_compile
, which turns the function into a regular (complied) Python function. So your solution is a good one. It's possible that it will also work correctly if you just apply the @pyscript_compile
to each of the two inner callback functions, instead of the whole function.
An alternative is to put the code into a module that you can import, since that will be treated as native compiled Python code. See the docs.
I'll remove that comment in the docs, since it's no longer true. When I first added @pyscript_compile
I wasn't sure it was a useful or appropriate feature.
from pyscript.
Disappointingly, YAML -> Python Object fails too.
MVP:
from enum import Enum, Flag, auto
import yaml
Action = Flag('Action', ['Press', 'Hold', 'TerminateHold', 'Indeterminate', 'Up', 'Down', 'Left', 'Right', 'Center'])
def Action_constructor(loader, node):
value = loader.construct_scalar(node)
values = value.split('|')
action_obj = Action(0)
for action in values:
action_obj |= Action[action]
return action_obj
yaml.add_constructor(u'!Action', Action_constructor)
On a Debian host:
In [28]: yaml.load("!Action 'Hold|TerminateHold'\n", Loader=yaml.FullLoader)
['Hold', 'TerminateHold']
Out[28]: <Action.TerminateHold|Hold: 6>
In PyScript, it does not error, but it does not return a useable object either:
log.info(yaml.load("!Action 'Hold'", Loader=yaml.Loader))
->
2023-10-23 22:38:36.544 INFO (MainThread) [custom_components.pyscript.file.example.async_foo] <coroutine object EvalFuncVar.__call__ at 0x7f7477c220>
from pyscript.
Ok so, shoving things into a @pyscript_compile
tag makes them work as expected but is this a 'solution'? PyScript docs state this is not totally expected to stick around. 'This is an experimental feature and might change in the future.' unless I misunderstood what this means.
See it in action here: https://github.com/JacobLChrzanowski/HomeAssistant/blob/cbce3b1d5703c750a2df7261a7eb427a22f28b7d/CONFIG/pyscript/example.py#L170
@pyscript_compile
def test_func():
def Action_representer(dumper, data: Action | ActionMode):
"""
Custom representer for an enum.Flag subclass 'Action' to enable customized YAML dumping.
The function works by:
converting the binary representation of the Action value into a set of power-of-two components,
joining their corresponding Action names with '|',
and then representing the result as a scalar in the YAML format
Args:
dumper: YAML dumper instance.
data (Action): The Action object to be represented in the YAML format.
Returns:
Represents the Action object as a scalar in the custom YAML format.
"""
class_name = f"!{data.__class__.__name__}"
binary_str = bin(data.value)[2:][::-1]
binary_pieces = [2**(i+0) for i, bit in enumerate(binary_str) if bit == '1']
repr_str = '|'.join([Action(x).name for x in binary_pieces])
return dumper.represent_scalar(class_name, repr_str)
yaml.add_representer(Action, Action_representer)
yaml.add_representer(ActionMode, Action_representer)
def Action_constructor(loader, node):
value = loader.construct_scalar(node)
values = value.split('|')
action_obj = Action(0)
for action in values:
action_obj |= Action[action]
return action_obj
yaml.add_constructor(u'!Action', Action_constructor)
from pyscript.
Sorry, I read your answer and implemented fixes over a month ago, totally forgot to reply!
Thanks @craigbarratt !
from pyscript.
Related Issues (20)
- 2023.12 Beta - state.set not setting state HOT 1
- [Feature Request] Error/warning when function name is duplicated in code
- Even with supports_response, service is not returning anything HOT 2
- not implemented ast ast_generatorexp HOT 1
- can not import library after reboot of HA
- Expose home assistant jinja template functions HOT 1
- Croniter version conflict HOT 1
- "MQTT entity name starts with the device name in your config"
- Feature Request: Make apps configurable from Home assistant UI
- Feature Request: exclude from recorder
- attribute changes not detected
- "async with" statement fails without target variable assignment
- Newbie help running Python script under pyscript as a service HOT 2
- Translated state HOT 1
- Template evaluation HOT 2
- Exception in <file.pv_excess_control.on_time> line 246 HOT 2
- Issues using yaml module in pyscript HOT 2
- Python 3.11 support removed from Home Assistant HOT 4
- помогите с IMPORT в home asistant HOT 1
- PyRight LSP HOT 9
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pyscript.