Way to use dot notation to refer to states in a state machine #15694
-
I'm experienced writing C++ code in Arduino but am just starting in micropython. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
You can use special methods of dict in Python to implement "dot notation". This simple module shows you how: # dotdict.py
_B='No such attribute: '
class Dot(dict):
def __getattr__(B,N):
if N in B:return B[N]
else:raise AttributeError(_B+N)
def __setattr__(B,N,V):
B[N]=V
def __delattr__(B,N):
if N in B:del B[N]
else:raise AttributeError(_B+N) You can then use the class as shown below: Use Ctrl-D to exit, Ctrl-E for paste mode
>>> from dotdict import Dot
>>> state=Dot()
>>> state.idle=1
>>> state.triggered=2
>>> state.lockout=3
>>> current_state=state.idle
>>> current_state
1
>>> state
{'triggered': 2, 'idle': 1, 'lockout': 3}
>>> if current_state==state.idle: print('Idle state')
...
Idle state
>>> del state.stop
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dotdict.py", line 14, in __delattr__
AttributeError: No such attribute: stop
>>> del state.triggered
>>> state
{'idle': 1, 'lockout': 3} Hope this is of some use. |
Beta Was this translation helpful? Give feedback.
-
docs/library/enum.rst: Add Enum class. #16842 Inspired by @shariltumin |
Beta Was this translation helpful? Give feedback.
-
Implementation in: |
Beta Was this translation helpful? Give feedback.
You can use special methods of dict in Python to implement "dot notation". This simple module shows you how:
You can then use the class as shown below: