pyscript icon indicating copy to clipboard operation
pyscript copied to clipboard

state.persist with defined default_value does not initialize pyscript.<attribute>

Open maciejmatczak opened this issue 2 years ago • 3 comments

Hello, I have a trouble with using a state.persist with a default value.

I expected, that whenever I register new state to be persistent, the attribute of pyscript module will be available. It looks like the attribute of the pyscript module does not get initialize if I do provide a default value, though.

import pyscript


DEVICE_ID = "xyz"


state.persist('pyscript.something_state', default_value=0)


@event_trigger("zha_event", f"device_id == '{DEVICE_ID}' and command == 'single'")
def switch_single(**kwargs):
    pyscript.something_state += 1
    log.info(f"Got clicked {pyscript.something_state} times")

Yields:

pyscript.something_state += 1
^
AttributeError: module 'pyscript' has no attribute 'something_state'

I suppose I might use try/except to initialize it on my own (as mentioned in https://github.com/custom-components/pyscript/issues/96#issuecomment-735214382 by @dlashua), but shouldn't it be done by state.persist(..., default_value=<value>)?

maciejmatczak avatar Feb 26 '23 13:02 maciejmatczak

That is a python error. if you assign a value defined in an other scope this one is assumed local while if you only read it it's assume global by default. Add the line bellow after your def global pyscript.something_state

For more details, you can have a look at https://docs.python.org/3/reference/simple_stmts.html#the-global-statement

dominig avatar Mar 11 '23 14:03 dominig

Hey @dominig, that would be UnboundLocalError, wouldn't it?

Edit: I can comment the "write" statement and you would see same error on a log line, when we only read.

maciejmatczak avatar Mar 11 '23 14:03 maciejmatczak

Remember that state variable are typed as string. To do math on them you must convert in as int try with the global line pyscript.something_state= int(pyscript.something_state)+1

dominig avatar Mar 11 '23 15:03 dominig