core.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. """
  2. transitions.core
  3. ----------------
  4. This module contains the central parts of transitions which are the state machine logic, state
  5. and transition concepts.
  6. """
  7. try:
  8. from builtins import object
  9. except ImportError:
  10. # python2
  11. pass
  12. try:
  13. # Enums are supported for Python 3.4+ and Python 2.7 with enum34 package installed
  14. from enum import Enum, EnumMeta
  15. except ImportError:
  16. # If enum is not available, create dummy classes for type checks
  17. class Enum:
  18. pass
  19. class EnumMeta:
  20. pass
  21. import inspect
  22. import itertools
  23. import logging
  24. from collections import OrderedDict, defaultdict, deque
  25. from functools import partial
  26. from six import string_types
  27. _LOGGER = logging.getLogger(__name__)
  28. _LOGGER.addHandler(logging.NullHandler())
  29. def listify(obj):
  30. """Wraps a passed object into a list in case it has not been a list, tuple before.
  31. Returns an empty list in case ``obj`` is None.
  32. Args:
  33. obj: instance to be converted into a list.
  34. Returns:
  35. list: May also return a tuple in case ``obj`` has been a tuple before.
  36. """
  37. if obj is None:
  38. return []
  39. return obj if isinstance(obj, (list, tuple, EnumMeta)) else [obj]
  40. def _prep_ordered_arg(desired_length, arguments=None):
  41. """Ensure list of arguments passed to add_ordered_transitions has the proper length.
  42. Expands the given arguments and apply same condition, callback
  43. to all transitions if only one has been given.
  44. Args:
  45. desired_length (int): The size of the resulting list
  46. arguments (optional[str, reference or list]): Parameters to be expanded.
  47. Returns:
  48. list: Parameter sets with the desired length.
  49. """
  50. arguments = listify(arguments) if arguments is not None else [None]
  51. if len(arguments) != desired_length and len(arguments) != 1:
  52. raise ValueError("Argument length must be either 1 or the same length as "
  53. "the number of transitions.")
  54. if len(arguments) == 1:
  55. return arguments * desired_length
  56. return arguments
  57. class State(object):
  58. """A persistent representation of a state managed by a ``Machine``.
  59. Attributes:
  60. name (str): State name which is also assigned to the model(s).
  61. on_enter (list): Callbacks executed when a state is entered.
  62. on_exit (list): Callbacks executed when a state is exited.
  63. ignore_invalid_triggers (bool): Indicates if unhandled/invalid triggers should raise an exception.
  64. """
  65. # A list of dynamic methods which can be resolved by a ``Machine`` instance for convenience functions.
  66. # Dynamic methods for states must always start with `on_`!
  67. dynamic_methods = ['on_enter', 'on_exit']
  68. def __init__(self, name, on_enter=None, on_exit=None,
  69. ignore_invalid_triggers=None):
  70. """
  71. Args:
  72. name (str or Enum): The name of the state
  73. on_enter (str or list): Optional callable(s) to trigger when a
  74. state is entered. Can be either a string providing the name of
  75. a callable, or a list of strings.
  76. on_exit (str or list): Optional callable(s) to trigger when a
  77. state is exited. Can be either a string providing the name of a
  78. callable, or a list of strings.
  79. ignore_invalid_triggers (Boolean): Optional flag to indicate if
  80. unhandled/invalid triggers should raise an exception
  81. """
  82. self._name = name
  83. self.ignore_invalid_triggers = ignore_invalid_triggers
  84. self.on_enter = listify(on_enter) if on_enter else []
  85. self.on_exit = listify(on_exit) if on_exit else []
  86. @property
  87. def name(self):
  88. if isinstance(self._name, Enum):
  89. return self._name.name
  90. else:
  91. return self._name
  92. @property
  93. def value(self):
  94. return self._name
  95. def enter(self, event_data):
  96. """ Triggered when a state is entered. """
  97. _LOGGER.debug("%sEntering state %s. Processing callbacks...", event_data.machine.name, self.name)
  98. event_data.machine.callbacks(self.on_enter, event_data)
  99. _LOGGER.info("%sEntered state %s", event_data.machine.name, self.name)
  100. def exit(self, event_data):
  101. """ Triggered when a state is exited. """
  102. _LOGGER.debug("%sExiting state %s. Processing callbacks...", event_data.machine.name, self.name)
  103. event_data.machine.callbacks(self.on_exit, event_data)
  104. _LOGGER.info("%sExited state %s", event_data.machine.name, self.name)
  105. def add_callback(self, trigger, func):
  106. """ Add a new enter or exit callback.
  107. Args:
  108. trigger (str): The type of triggering event. Must be one of
  109. 'enter' or 'exit'.
  110. func (str): The name of the callback function.
  111. """
  112. callback_list = getattr(self, 'on_' + trigger)
  113. callback_list.append(func)
  114. def __repr__(self):
  115. return "<%s('%s')@%s>" % (type(self).__name__, self.name, id(self))
  116. class Condition(object):
  117. """ A helper class to call condition checks in the intended way.
  118. Attributes:
  119. func (callable): The function to call for the condition check
  120. target (bool): Indicates the target state--i.e., when True,
  121. the condition-checking callback should return True to pass,
  122. and when False, the callback should return False to pass.
  123. """
  124. def __init__(self, func, target=True):
  125. """
  126. Args:
  127. func (str): Name of the condition-checking callable
  128. target (bool): Indicates the target state--i.e., when True,
  129. the condition-checking callback should return True to pass,
  130. and when False, the callback should return False to pass.
  131. Notes:
  132. This class should not be initialized or called from outside a
  133. Transition instance, and exists at module level (rather than
  134. nesting under the transition class) only because of a bug in
  135. dill that prevents serialization under Python 2.7.
  136. """
  137. self.func = func
  138. self.target = target
  139. def check(self, event_data):
  140. """ Check whether the condition passes.
  141. Args:
  142. event_data (EventData): An EventData instance to pass to the
  143. condition (if event sending is enabled) or to extract arguments
  144. from (if event sending is disabled). Also contains the data
  145. model attached to the current machine which is used to invoke
  146. the condition.
  147. """
  148. predicate = event_data.machine.resolve_callable(self.func, event_data)
  149. if event_data.machine.send_event:
  150. return predicate(event_data) == self.target
  151. return predicate(*event_data.args, **event_data.kwargs) == self.target
  152. def __repr__(self):
  153. return "<%s(%s)@%s>" % (type(self).__name__, self.func, id(self))
  154. class Transition(object):
  155. """ Representation of a transition managed by a ``Machine`` instance.
  156. Attributes:
  157. source (str): Source state of the transition.
  158. dest (str): Destination state of the transition.
  159. prepare (list): Callbacks executed before conditions checks.
  160. conditions (list): Callbacks evaluated to determine if
  161. the transition should be executed.
  162. before (list): Callbacks executed before the transition is executed
  163. but only if condition checks have been successful.
  164. after (list): Callbacks executed after the transition is executed
  165. but only if condition checks have been successful.
  166. """
  167. dynamic_methods = ['before', 'after', 'prepare']
  168. """ A list of dynamic methods which can be resolved by a ``Machine`` instance for convenience functions. """
  169. condition_cls = Condition
  170. """ The class used to wrap condition checks. Can be replaced to alter condition resolution behaviour
  171. (e.g. OR instead of AND for 'conditions' or AND instead of OR for 'unless') """
  172. def __init__(self, source, dest, conditions=None, unless=None, before=None,
  173. after=None, prepare=None):
  174. """
  175. Args:
  176. source (str): The name of the source State.
  177. dest (str): The name of the destination State.
  178. conditions (optional[str, callable or list]): Condition(s) that must pass in order for
  179. the transition to take place. Either a string providing the
  180. name of a callable, or a list of callables. For the transition
  181. to occur, ALL callables must return True.
  182. unless (optional[str, callable or list]): Condition(s) that must return False in order
  183. for the transition to occur. Behaves just like conditions arg
  184. otherwise.
  185. before (optional[str, callable or list]): callbacks to trigger before the
  186. transition.
  187. after (optional[str, callable or list]): callbacks to trigger after the transition.
  188. prepare (optional[str, callable or list]): callbacks to trigger before conditions are checked
  189. """
  190. self.source = source
  191. self.dest = dest
  192. self.prepare = [] if prepare is None else listify(prepare)
  193. self.before = [] if before is None else listify(before)
  194. self.after = [] if after is None else listify(after)
  195. self.conditions = []
  196. if conditions is not None:
  197. for cond in listify(conditions):
  198. self.conditions.append(self.condition_cls(cond))
  199. if unless is not None:
  200. for cond in listify(unless):
  201. self.conditions.append(self.condition_cls(cond, target=False))
  202. def _eval_conditions(self, event_data):
  203. for cond in self.conditions:
  204. if not cond.check(event_data):
  205. _LOGGER.debug("%sTransition condition failed: %s() does not return %s. Transition halted.",
  206. event_data.machine.name, cond.func, cond.target)
  207. return False
  208. return True
  209. def execute(self, event_data):
  210. """ Execute the transition.
  211. Args:
  212. event_data: An instance of class EventData.
  213. Returns: boolean indicating whether or not the transition was
  214. successfully executed (True if successful, False if not).
  215. """
  216. _LOGGER.debug("%sInitiating transition from state %s to state %s...",
  217. event_data.machine.name, self.source, self.dest)
  218. event_data.machine.callbacks(self.prepare, event_data)
  219. _LOGGER.debug("%sExecuted callbacks before conditions.", event_data.machine.name)
  220. if not self._eval_conditions(event_data):
  221. return False
  222. event_data.machine.callbacks(itertools.chain(event_data.machine.before_state_change, self.before), event_data)
  223. _LOGGER.debug("%sExecuted callback before transition.", event_data.machine.name)
  224. if self.dest: # if self.dest is None this is an internal transition with no actual state change
  225. self._change_state(event_data)
  226. event_data.machine.callbacks(itertools.chain(self.after, event_data.machine.after_state_change), event_data)
  227. _LOGGER.debug("%sExecuted callback after transition.", event_data.machine.name)
  228. return True
  229. def _change_state(self, event_data):
  230. event_data.machine.get_state(self.source).exit(event_data)
  231. event_data.machine.set_state(self.dest, event_data.model)
  232. event_data.update(getattr(event_data.model, event_data.machine.model_attribute))
  233. event_data.machine.get_state(self.dest).enter(event_data)
  234. def add_callback(self, trigger, func):
  235. """ Add a new before, after, or prepare callback.
  236. Args:
  237. trigger (str): The type of triggering event. Must be one of
  238. 'before', 'after' or 'prepare'.
  239. func (str): The name of the callback function.
  240. """
  241. callback_list = getattr(self, trigger)
  242. callback_list.append(func)
  243. def __repr__(self):
  244. return "<%s('%s', '%s')@%s>" % (type(self).__name__,
  245. self.source, self.dest, id(self))
  246. class EventData(object):
  247. """ Collection of relevant data related to the ongoing transition attempt.
  248. Attributes:
  249. state (State): The State from which the Event was triggered.
  250. event (Event): The triggering Event.
  251. machine (Machine): The current Machine instance.
  252. model (object): The model/object the machine is bound to.
  253. args (list): Optional positional arguments from trigger method
  254. to store internally for possible later use.
  255. kwargs (dict): Optional keyword arguments from trigger method
  256. to store internally for possible later use.
  257. transition (Transition): Currently active transition. Will be assigned during triggering.
  258. error (Error): In case a triggered event causes an Error, it is assigned here and passed on.
  259. result (bool): True in case a transition has been successful, False otherwise.
  260. """
  261. def __init__(self, state, event, machine, model, args, kwargs):
  262. """
  263. Args:
  264. state (State): The State from which the Event was triggered.
  265. event (Event): The triggering Event.
  266. machine (Machine): The current Machine instance.
  267. model (object): The model/object the machine is bound to.
  268. args (tuple): Optional positional arguments from trigger method
  269. to store internally for possible later use.
  270. kwargs (dict): Optional keyword arguments from trigger method
  271. to store internally for possible later use.
  272. """
  273. self.state = state
  274. self.event = event
  275. self.machine = machine
  276. self.model = model
  277. self.args = args
  278. self.kwargs = kwargs
  279. self.transition = None
  280. self.error = None
  281. self.result = False
  282. def update(self, state):
  283. """ Updates the EventData object with the passed state.
  284. Attributes:
  285. state (State, str or Enum): The state object, enum member or string to assign to EventData.
  286. """
  287. if not isinstance(state, State):
  288. self.state = self.machine.get_state(state)
  289. def __repr__(self):
  290. return "<%s('%s', %s)@%s>" % (type(self).__name__, self.state,
  291. getattr(self, 'transition'), id(self))
  292. class Event(object):
  293. """ A collection of transitions assigned to the same trigger
  294. """
  295. def __init__(self, name, machine):
  296. """
  297. Args:
  298. name (str): The name of the event, which is also the name of the
  299. triggering callable (e.g., 'advance' implies an advance()
  300. method).
  301. machine (Machine): The current Machine instance.
  302. """
  303. self.name = name
  304. self.machine = machine
  305. self.transitions = defaultdict(list)
  306. def add_transition(self, transition):
  307. """ Add a transition to the list of potential transitions.
  308. Args:
  309. transition (Transition): The Transition instance to add to the
  310. list.
  311. """
  312. self.transitions[transition.source].append(transition)
  313. def trigger(self, model, *args, **kwargs):
  314. """ Serially execute all transitions that match the current state,
  315. halting as soon as one successfully completes.
  316. Args:
  317. args and kwargs: Optional positional or named arguments that will
  318. be passed onto the EventData object, enabling arbitrary state
  319. information to be passed on to downstream triggered functions.
  320. Returns: boolean indicating whether or not a transition was
  321. successfully executed (True if successful, False if not).
  322. """
  323. func = partial(self._trigger, model, *args, **kwargs)
  324. # pylint: disable=protected-access
  325. # noinspection PyProtectedMember
  326. # Machine._process should not be called somewhere else. That's why it should not be exposed
  327. # to Machine users.
  328. return self.machine._process(func)
  329. def _trigger(self, model, *args, **kwargs):
  330. """ Internal trigger function called by the ``Machine`` instance. This should not
  331. be called directly but via the public method ``Machine.trigger``.
  332. """
  333. state = self.machine.get_model_state(model)
  334. if state.name not in self.transitions:
  335. msg = "%sCan't trigger event %s from state %s!" % (self.machine.name, self.name,
  336. state.name)
  337. ignore = state.ignore_invalid_triggers if state.ignore_invalid_triggers is not None \
  338. else self.machine.ignore_invalid_triggers
  339. if ignore:
  340. _LOGGER.warning(msg)
  341. return False
  342. else:
  343. raise MachineError(msg)
  344. event_data = EventData(state, self, self.machine, model, args=args, kwargs=kwargs)
  345. return self._process(event_data)
  346. def _process(self, event_data):
  347. self.machine.callbacks(self.machine.prepare_event, event_data)
  348. _LOGGER.debug("%sExecuted machine preparation callbacks before conditions.", self.machine.name)
  349. try:
  350. for trans in self.transitions[event_data.state.name]:
  351. event_data.transition = trans
  352. if trans.execute(event_data):
  353. event_data.result = True
  354. break
  355. except Exception as err:
  356. event_data.error = err
  357. raise
  358. finally:
  359. self.machine.callbacks(self.machine.finalize_event, event_data)
  360. _LOGGER.debug("%sExecuted machine finalize callbacks", self.machine.name)
  361. return event_data.result
  362. def __repr__(self):
  363. return "<%s('%s')@%s>" % (type(self).__name__, self.name, id(self))
  364. def add_callback(self, trigger, func):
  365. """ Add a new before or after callback to all available transitions.
  366. Args:
  367. trigger (str): The type of triggering event. Must be one of
  368. 'before', 'after' or 'prepare'.
  369. func (str): The name of the callback function.
  370. """
  371. for trans in itertools.chain(*self.transitions.values()):
  372. trans.add_callback(trigger, func)
  373. class Machine(object):
  374. """ Machine manages states, transitions and models. In case it is initialized without a specific model
  375. (or specifically no model), it will also act as a model itself. Machine takes also care of decorating
  376. models with conveniences functions related to added transitions and states during runtime.
  377. Attributes:
  378. states (OrderedDict): Collection of all registered states.
  379. events (dict): Collection of transitions ordered by trigger/event.
  380. models (list): List of models attached to the machine.
  381. initial (str): Name of the initial state for new models.
  382. prepare_event (list): Callbacks executed when an event is triggered.
  383. before_state_change (list): Callbacks executed after condition checks but before transition is conducted.
  384. Callbacks will be executed BEFORE the custom callbacks assigned to the transition.
  385. after_state_change (list): Callbacks executed after the transition has been conducted.
  386. Callbacks will be executed AFTER the custom callbacks assigned to the transition.
  387. finalize_event (list): Callbacks will be executed after all transitions callbacks have been executed.
  388. Callbacks mentioned here will also be called if a transition or condition check raised an error.
  389. queued (bool): Whether transitions in callbacks should be executed immediately (False) or sequentially.
  390. send_event (bool): When True, any arguments passed to trigger methods will be wrapped in an EventData
  391. object, allowing indirect and encapsulated access to data. When False, all positional and keyword
  392. arguments will be passed directly to all callback methods.
  393. auto_transitions (bool): When True (default), every state will automatically have an associated
  394. to_{state}() convenience trigger in the base model.
  395. ignore_invalid_triggers (bool): When True, any calls to trigger methods that are not valid for the
  396. present state (e.g., calling an a_to_b() trigger when the current state is c) will be silently
  397. ignored rather than raising an invalid transition exception.
  398. name (str): Name of the ``Machine`` instance mainly used for easier log message distinction.
  399. """
  400. separator = '_' # separates callback type from state/transition name
  401. wildcard_all = '*' # will be expanded to ALL states
  402. wildcard_same = '=' # will be expanded to source state
  403. state_cls = State
  404. transition_cls = Transition
  405. event_cls = Event
  406. def __init__(self, model='self', states=None, initial='initial', transitions=None,
  407. send_event=False, auto_transitions=True,
  408. ordered_transitions=False, ignore_invalid_triggers=None,
  409. before_state_change=None, after_state_change=None, name=None,
  410. queued=False, prepare_event=None, finalize_event=None, model_attribute='state', **kwargs):
  411. """
  412. Args:
  413. model (object or list): The object(s) whose states we want to manage. If 'self',
  414. the current Machine instance will be used the model (i.e., all
  415. triggering events will be attached to the Machine itself). Note that an empty list
  416. is treated like no model.
  417. states (list or Enum): A list or enumeration of valid states. Each list element can be either a
  418. string, an enum member or a State instance. If string or enum member, a new generic State
  419. instance will be created that is named according to the string or enum member's name.
  420. initial (str, Enum or State): The initial state of the passed model[s].
  421. transitions (list): An optional list of transitions. Each element
  422. is a dictionary of named arguments to be passed onto the
  423. Transition initializer.
  424. send_event (boolean): When True, any arguments passed to trigger
  425. methods will be wrapped in an EventData object, allowing
  426. indirect and encapsulated access to data. When False, all
  427. positional and keyword arguments will be passed directly to all
  428. callback methods.
  429. auto_transitions (boolean): When True (default), every state will
  430. automatically have an associated to_{state}() convenience
  431. trigger in the base model.
  432. ordered_transitions (boolean): Convenience argument that calls
  433. add_ordered_transitions() at the end of initialization if set
  434. to True.
  435. ignore_invalid_triggers: when True, any calls to trigger methods
  436. that are not valid for the present state (e.g., calling an
  437. a_to_b() trigger when the current state is c) will be silently
  438. ignored rather than raising an invalid transition exception.
  439. before_state_change: A callable called on every change state before
  440. the transition happened. It receives the very same args as normal
  441. callbacks.
  442. after_state_change: A callable called on every change state after
  443. the transition happened. It receives the very same args as normal
  444. callbacks.
  445. name: If a name is set, it will be used as a prefix for logger output
  446. queued (boolean): When True, processes transitions sequentially. A trigger
  447. executed in a state callback function will be queued and executed later.
  448. Due to the nature of the queued processing, all transitions will
  449. _always_ return True since conditional checks cannot be conducted at queueing time.
  450. prepare_event: A callable called on for before possible transitions will be processed.
  451. It receives the very same args as normal callbacks.
  452. finalize_event: A callable called on for each triggered event after transitions have been processed.
  453. This is also called when a transition raises an exception.
  454. **kwargs additional arguments passed to next class in MRO. This can be ignored in most cases.
  455. """
  456. # calling super in case `Machine` is used as a mix in
  457. # all keyword arguments should be consumed by now if this is not the case
  458. try:
  459. super(Machine, self).__init__(**kwargs)
  460. except TypeError as err:
  461. raise ValueError('Passing arguments {0} caused an inheritance error: {1}'.format(kwargs.keys(), err))
  462. # initialize protected attributes first
  463. self._queued = queued
  464. self._transition_queue = deque()
  465. self._before_state_change = []
  466. self._after_state_change = []
  467. self._prepare_event = []
  468. self._finalize_event = []
  469. self._initial = None
  470. self.states = OrderedDict()
  471. self.events = {}
  472. self.send_event = send_event
  473. self.auto_transitions = auto_transitions
  474. self.ignore_invalid_triggers = ignore_invalid_triggers
  475. self.prepare_event = prepare_event
  476. self.before_state_change = before_state_change
  477. self.after_state_change = after_state_change
  478. self.finalize_event = finalize_event
  479. self.name = name + ": " if name is not None else ""
  480. self.model_attribute = model_attribute
  481. self.models = []
  482. if states is not None:
  483. self.add_states(states)
  484. if initial is not None:
  485. self.initial = initial
  486. if transitions is not None:
  487. self.add_transitions(transitions)
  488. if ordered_transitions:
  489. self.add_ordered_transitions()
  490. if model:
  491. self.add_model(model)
  492. def add_model(self, model, initial=None):
  493. """ Register a model with the state machine, initializing triggers and callbacks. """
  494. models = listify(model)
  495. if initial is None:
  496. if self.initial is None:
  497. raise ValueError("No initial state configured for machine, must specify when adding model.")
  498. else:
  499. initial = self.initial
  500. for mod in models:
  501. mod = self if mod == 'self' else mod
  502. if mod not in self.models:
  503. self._checked_assignment(mod, 'trigger', partial(self._get_trigger, mod))
  504. for trigger in self.events:
  505. self._add_trigger_to_model(trigger, mod)
  506. for state in self.states.values():
  507. self._add_model_to_state(state, mod)
  508. self.set_state(initial, model=mod)
  509. self.models.append(mod)
  510. def remove_model(self, model):
  511. """ Remove a model from the state machine. The model will still contain all previously added triggers
  512. and callbacks, but will not receive updates when states or transitions are added to the Machine. """
  513. models = listify(model)
  514. for mod in models:
  515. self.models.remove(mod)
  516. @classmethod
  517. def _create_transition(cls, *args, **kwargs):
  518. return cls.transition_cls(*args, **kwargs)
  519. @classmethod
  520. def _create_event(cls, *args, **kwargs):
  521. return cls.event_cls(*args, **kwargs)
  522. @classmethod
  523. def _create_state(cls, *args, **kwargs):
  524. return cls.state_cls(*args, **kwargs)
  525. @property
  526. def initial(self):
  527. """ Return the initial state. """
  528. return self._initial
  529. @initial.setter
  530. def initial(self, value):
  531. if isinstance(value, State):
  532. if value.name not in self.states:
  533. self.add_state(value)
  534. else:
  535. _ = self._has_state(value, raise_error=True)
  536. self._initial = value.name
  537. else:
  538. state_name = value.name if isinstance(value, Enum) else value
  539. if state_name not in self.states:
  540. self.add_state(state_name)
  541. self._initial = state_name
  542. @property
  543. def has_queue(self):
  544. """ Return boolean indicating if machine has queue or not """
  545. return self._queued
  546. @property
  547. def model(self):
  548. """ List of models attached to the machine. For backwards compatibility, the property will
  549. return the model instance itself instead of the underlying list if there is only one attached
  550. to the machine.
  551. """
  552. if len(self.models) == 1:
  553. return self.models[0]
  554. return self.models
  555. @property
  556. def before_state_change(self):
  557. """Callbacks executed after condition checks but before transition is conducted.
  558. Callbacks will be executed BEFORE the custom callbacks assigned to the transition."""
  559. return self._before_state_change
  560. # this should make sure that _before_state_change is always a list
  561. @before_state_change.setter
  562. def before_state_change(self, value):
  563. self._before_state_change = listify(value)
  564. @property
  565. def after_state_change(self):
  566. """Callbacks executed after the transition has been conducted.
  567. Callbacks will be executed AFTER the custom callbacks assigned to the transition."""
  568. return self._after_state_change
  569. # this should make sure that _after_state_change is always a list
  570. @after_state_change.setter
  571. def after_state_change(self, value):
  572. self._after_state_change = listify(value)
  573. @property
  574. def prepare_event(self):
  575. """Callbacks executed when an event is triggered."""
  576. return self._prepare_event
  577. # this should make sure that prepare_event is always a list
  578. @prepare_event.setter
  579. def prepare_event(self, value):
  580. self._prepare_event = listify(value)
  581. @property
  582. def finalize_event(self):
  583. """Callbacks will be executed after all transitions callbacks have been executed.
  584. Callbacks mentioned here will also be called if a transition or condition check raised an error."""
  585. return self._finalize_event
  586. # this should make sure that finalize_event is always a list
  587. @finalize_event.setter
  588. def finalize_event(self, value):
  589. self._finalize_event = listify(value)
  590. def get_state(self, state):
  591. """ Return the State instance with the passed name. """
  592. if isinstance(state, Enum):
  593. state = state.name
  594. if state not in self.states:
  595. raise ValueError("State '%s' is not a registered state." % state)
  596. return self.states[state]
  597. # In theory this function could be static. This however causes some issues related to inheritance and
  598. # pickling down the chain.
  599. def is_state(self, state, model):
  600. """ Check whether the current state matches the named state. This function is not called directly
  601. but assigned as partials to model instances (e.g. is_A -> partial(_is_state, 'A', model)).
  602. Args:
  603. state (str): name of the checked state
  604. model: model to be checked
  605. Returns:
  606. bool: Whether the model's current state is state.
  607. """
  608. return getattr(model, self.model_attribute) == state
  609. def get_model_state(self, model):
  610. return self.get_state(getattr(model, self.model_attribute))
  611. def set_state(self, state, model=None):
  612. """
  613. Set the current state.
  614. Args:
  615. state (str or Enum or State): value of state to be set
  616. model (optional[object]): targeted model; if not set, all models will be set to 'state'
  617. """
  618. if not isinstance(state, State):
  619. state = self.get_state(state)
  620. models = self.models if model is None else listify(model)
  621. for mod in models:
  622. setattr(mod, self.model_attribute, state.value)
  623. def add_state(self, *args, **kwargs):
  624. """ Alias for add_states. """
  625. self.add_states(*args, **kwargs)
  626. def add_states(self, states, on_enter=None, on_exit=None,
  627. ignore_invalid_triggers=None, **kwargs):
  628. """ Add new state(s).
  629. Args:
  630. states (list, str, dict, Enum or State): a list, a State instance, the
  631. name of a new state, an enumeration (member) or a dict with keywords to pass on to the
  632. State initializer. If a list, each element can be a string, State or enumeration member.
  633. on_enter (str or list): callbacks to trigger when the state is
  634. entered. Only valid if first argument is string.
  635. on_exit (str or list): callbacks to trigger when the state is
  636. exited. Only valid if first argument is string.
  637. ignore_invalid_triggers: when True, any calls to trigger methods
  638. that are not valid for the present state (e.g., calling an
  639. a_to_b() trigger when the current state is c) will be silently
  640. ignored rather than raising an invalid transition exception.
  641. Note that this argument takes precedence over the same
  642. argument defined at the Machine level, and is in turn
  643. overridden by any ignore_invalid_triggers explicitly
  644. passed in an individual state's initialization arguments.
  645. **kwargs additional keyword arguments used by state mixins.
  646. """
  647. ignore = ignore_invalid_triggers
  648. if ignore is None:
  649. ignore = self.ignore_invalid_triggers
  650. states = listify(states)
  651. for state in states:
  652. if isinstance(state, (string_types, Enum)):
  653. state = self._create_state(
  654. state, on_enter=on_enter, on_exit=on_exit,
  655. ignore_invalid_triggers=ignore, **kwargs)
  656. elif isinstance(state, dict):
  657. if 'ignore_invalid_triggers' not in state:
  658. state['ignore_invalid_triggers'] = ignore
  659. state = self._create_state(**state)
  660. self.states[state.name] = state
  661. for model in self.models:
  662. self._add_model_to_state(state, model)
  663. if self.auto_transitions:
  664. for a_state in self.states.keys():
  665. # add all states as sources to auto transitions 'to_<state>' with dest <state>
  666. if a_state == state.name:
  667. self.add_transition('to_%s' % a_state, self.wildcard_all, a_state)
  668. # add auto transition with source <state> to <a_state>
  669. else:
  670. self.add_transition('to_%s' % a_state, state.name, a_state)
  671. def _add_model_to_state(self, state, model):
  672. self._checked_assignment(model, 'is_%s' % state.name, partial(self.is_state, state.value, model))
  673. # Add dynamic method callbacks (enter/exit) if there are existing bound methods in the model
  674. # except if they are already mentioned in 'on_enter/exit' of the defined state
  675. for callback in self.state_cls.dynamic_methods:
  676. method = "{0}_{1}".format(callback, state.name)
  677. if hasattr(model, method) and inspect.ismethod(getattr(model, method)) and \
  678. method not in getattr(state, callback):
  679. state.add_callback(callback[3:], method)
  680. def _checked_assignment(self, model, name, func):
  681. if hasattr(model, name):
  682. _LOGGER.warning("%sModel already contains an attribute '%s'. Skip binding.", self.name, name)
  683. else:
  684. setattr(model, name, func)
  685. def _add_trigger_to_model(self, trigger, model):
  686. self._checked_assignment(model, trigger, partial(self.events[trigger].trigger, model))
  687. def _get_trigger(self, model, trigger_name, *args, **kwargs):
  688. """Convenience function added to the model to trigger events by name.
  689. Args:
  690. model (object): Model with assigned event trigger.
  691. machine (Machine): The machine containing the evaluated events.
  692. trigger_name (str): Name of the trigger to be called.
  693. *args: Variable length argument list which is passed to the triggered event.
  694. **kwargs: Arbitrary keyword arguments which is passed to the triggered event.
  695. Returns:
  696. bool: True if a transitions has been conducted or the trigger event has been queued.
  697. """
  698. try:
  699. event = self.events[trigger_name]
  700. except KeyError:
  701. raise AttributeError("Do not know event named '%s'." % trigger_name)
  702. return event.trigger(model, *args, **kwargs)
  703. def get_triggers(self, *args):
  704. """ Collects all triggers FROM certain states.
  705. Args:
  706. *args: Tuple of source states.
  707. Returns:
  708. list of transition/trigger names.
  709. """
  710. states = set(args)
  711. return [t for (t, ev) in self.events.items() if any(state in ev.transitions for state in states)]
  712. def add_transition(self, trigger, source, dest, conditions=None,
  713. unless=None, before=None, after=None, prepare=None, **kwargs):
  714. """ Create a new Transition instance and add it to the internal list.
  715. Args:
  716. trigger (str): The name of the method that will trigger the
  717. transition. This will be attached to the currently specified
  718. model (e.g., passing trigger='advance' will create a new
  719. advance() method in the model that triggers the transition.)
  720. source(str or list): The name of the source state--i.e., the state we
  721. are transitioning away from. This can be a single state, a
  722. list of states or an asterisk for all states.
  723. dest (str): The name of the destination State--i.e., the state
  724. we are transitioning into. This can be a single state or an
  725. equal sign to specify that the transition should be reflexive
  726. so that the destination will be the same as the source for
  727. every given source. If dest is None, this transition will be
  728. an internal transition (exit/enter callbacks won't be processed).
  729. conditions (str or list): Condition(s) that must pass in order
  730. for the transition to take place. Either a list providing the
  731. name of a callable, or a list of callables. For the transition
  732. to occur, ALL callables must return True.
  733. unless (str or list): Condition(s) that must return False in order
  734. for the transition to occur. Behaves just like conditions arg
  735. otherwise.
  736. before (str or list): Callables to call before the transition.
  737. after (str or list): Callables to call after the transition.
  738. prepare (str or list): Callables to call when the trigger is activated
  739. **kwargs: Additional arguments which can be passed to the created transition.
  740. This is useful if you plan to extend Machine.Transition and require more parameters.
  741. """
  742. if trigger == self.model_attribute:
  743. raise ValueError("Trigger name cannot be same as model attribute name.")
  744. if trigger not in self.events:
  745. self.events[trigger] = self._create_event(trigger, self)
  746. for model in self.models:
  747. self._add_trigger_to_model(trigger, model)
  748. if source == self.wildcard_all:
  749. source = list(self.states.keys())
  750. else:
  751. # states are checked lazily which means we will only raise exceptions when the passed state
  752. # is a State object because of potential confusion (see issue #155 for more details)
  753. source = [s.name if isinstance(s, State) and self._has_state(s, raise_error=True) or hasattr(s, 'name') else
  754. s for s in listify(source)]
  755. for state in source:
  756. if dest == self.wildcard_same:
  757. _dest = state
  758. elif dest:
  759. if isinstance(dest, State):
  760. _ = self._has_state(dest, raise_error=True)
  761. _dest = dest.name if hasattr(dest, 'name') else dest
  762. else:
  763. _dest = None
  764. _trans = self._create_transition(state, _dest, conditions, unless, before,
  765. after, prepare, **kwargs)
  766. self.events[trigger].add_transition(_trans)
  767. def add_transitions(self, transitions):
  768. """ Add several transitions.
  769. Args:
  770. transitions (list): A list of transitions.
  771. """
  772. for trans in listify(transitions):
  773. if isinstance(trans, list):
  774. self.add_transition(*trans)
  775. else:
  776. self.add_transition(**trans)
  777. def add_ordered_transitions(self, states=None, trigger='next_state',
  778. loop=True, loop_includes_initial=True,
  779. conditions=None, unless=None, before=None,
  780. after=None, prepare=None, **kwargs):
  781. """ Add a set of transitions that move linearly from state to state.
  782. Args:
  783. states (list): A list of state names defining the order of the
  784. transitions. E.g., ['A', 'B', 'C'] will generate transitions
  785. for A --> B, B --> C, and C --> A (if loop is True). If states
  786. is None, all states in the current instance will be used.
  787. trigger (str): The name of the trigger method that advances to
  788. the next state in the sequence.
  789. loop (boolean): Whether or not to add a transition from the last
  790. state to the first state.
  791. loop_includes_initial (boolean): If no initial state was defined in
  792. the machine, setting this to True will cause the _initial state
  793. placeholder to be included in the added transitions. This argument
  794. has no effect if the states argument is passed without the
  795. initial state included.
  796. conditions (str or list): Condition(s) that must pass in order
  797. for the transition to take place. Either a list providing the
  798. name of a callable, or a list of callables. For the transition
  799. to occur, ALL callables must return True.
  800. unless (str or list): Condition(s) that must return False in order
  801. for the transition to occur. Behaves just like conditions arg
  802. otherwise.
  803. before (str or list): Callables to call before the transition.
  804. after (str or list): Callables to call after the transition.
  805. prepare (str or list): Callables to call when the trigger is activated
  806. **kwargs: Additional arguments which can be passed to the created transition.
  807. This is useful if you plan to extend Machine.Transition and require more parameters.
  808. """
  809. if states is None:
  810. states = list(self.states.keys()) # need to listify for Python3
  811. len_transitions = len(states)
  812. if len_transitions < 2:
  813. raise ValueError("Can't create ordered transitions on a Machine "
  814. "with fewer than 2 states.")
  815. if not loop:
  816. len_transitions -= 1
  817. # ensure all args are the proper length
  818. conditions = _prep_ordered_arg(len_transitions, conditions)
  819. unless = _prep_ordered_arg(len_transitions, unless)
  820. before = _prep_ordered_arg(len_transitions, before)
  821. after = _prep_ordered_arg(len_transitions, after)
  822. prepare = _prep_ordered_arg(len_transitions, prepare)
  823. # reorder list so that the initial state is actually the first one
  824. try:
  825. idx = states.index(self._initial)
  826. states = states[idx:] + states[:idx]
  827. first_in_loop = states[0 if loop_includes_initial else 1]
  828. except ValueError:
  829. # since initial is not part of states it shouldn't be part of the loop either
  830. first_in_loop = states[0]
  831. for i in range(0, len(states) - 1):
  832. self.add_transition(trigger, states[i], states[i + 1],
  833. conditions=conditions[i],
  834. unless=unless[i],
  835. before=before[i],
  836. after=after[i],
  837. prepare=prepare[i],
  838. **kwargs)
  839. if loop:
  840. self.add_transition(trigger, states[-1],
  841. # omit initial if not loop_includes_initial
  842. first_in_loop,
  843. conditions=conditions[-1],
  844. unless=unless[-1],
  845. before=before[-1],
  846. after=after[-1],
  847. prepare=prepare[-1],
  848. **kwargs)
  849. def get_transitions(self, trigger="", source="*", dest="*"):
  850. """ Return the transitions from the Machine.
  851. Args:
  852. trigger (str): Trigger name of the transition.
  853. source (str): Limits removal to transitions from a certain state.
  854. dest (str): Limits removal to transitions to a certain state.
  855. """
  856. if trigger:
  857. events = (self.events[trigger], )
  858. else:
  859. events = self.events.values()
  860. transitions = []
  861. for event in events:
  862. transitions.extend(
  863. itertools.chain.from_iterable(event.transitions.values()))
  864. return [transition
  865. for transition in transitions
  866. if (transition.source, transition.dest) == (
  867. source if source != "*" else transition.source,
  868. dest if dest != "*" else transition.dest)]
  869. def remove_transition(self, trigger, source="*", dest="*"):
  870. """ Removes a transition from the Machine and all models.
  871. Args:
  872. trigger (str): Trigger name of the transition.
  873. source (str): Limits removal to transitions from a certain state.
  874. dest (str): Limits removal to transitions to a certain state.
  875. """
  876. source = listify(source) if source != "*" else source
  877. dest = listify(dest) if dest != "*" else dest
  878. # outer comprehension, keeps events if inner comprehension returns lists with length > 0
  879. tmp = {key: value for key, value in
  880. {k: [t for t in v
  881. # keep entries if source should not be filtered; same for dest.
  882. if (source != "*" and t.source not in source) or (dest != "*" and t.dest not in dest)]
  883. # }.items() takes the result of the inner comprehension and uses it
  884. # for the outer comprehension (see first line of comment)
  885. for k, v in self.events[trigger].transitions.items()}.items()
  886. if len(value) > 0}
  887. # convert dict back to defaultdict in case tmp is not empty
  888. if tmp:
  889. self.events[trigger].transitions = defaultdict(list, **tmp)
  890. # if no transition is left remove the trigger from the machine and all models
  891. else:
  892. for model in self.models:
  893. delattr(model, trigger)
  894. del self.events[trigger]
  895. def dispatch(self, trigger, *args, **kwargs):
  896. """ Trigger an event on all models assigned to the machine.
  897. Args:
  898. trigger (str): Event name
  899. *args (list): List of arguments passed to the event trigger
  900. **kwargs (dict): Dictionary of keyword arguments passed to the event trigger
  901. Returns:
  902. bool The truth value of all triggers combined with AND
  903. """
  904. return all([getattr(model, trigger)(*args, **kwargs) for model in self.models])
  905. def callbacks(self, funcs, event_data):
  906. """ Triggers a list of callbacks """
  907. for func in funcs:
  908. self.callback(func, event_data)
  909. _LOGGER.info("%sExecuted callback '%s'", self.name, func)
  910. def callback(self, func, event_data):
  911. """ Trigger a callback function with passed event_data parameters. In case func is a string,
  912. the callable will be resolved from the passed model in event_data. This function is not intended to
  913. be called directly but through state and transition callback definitions.
  914. Args:
  915. func (str or callable): The callback function.
  916. 1. First, if the func is callable, just call it
  917. 2. Second, we try to import string assuming it is a path to a func
  918. 3. Fallback to a model attribute
  919. event_data (EventData): An EventData instance to pass to the
  920. callback (if event sending is enabled) or to extract arguments
  921. from (if event sending is disabled).
  922. """
  923. func = self.resolve_callable(func, event_data)
  924. if self.send_event:
  925. func(event_data)
  926. else:
  927. func(*event_data.args, **event_data.kwargs)
  928. @staticmethod
  929. def resolve_callable(func, event_data):
  930. """ Converts a model's property name, method name or a path to a callable into a callable.
  931. If func is not a string it will be returned unaltered.
  932. Args:
  933. func (str or callable): Property name, method name or a path to a callable
  934. event_data (EventData): Currently processed event
  935. Returns:
  936. callable function resolved from string or func
  937. """
  938. if isinstance(func, string_types):
  939. try:
  940. func = getattr(event_data.model, func)
  941. if not callable(func): # if a property or some other not callable attribute was passed
  942. def func_wrapper(*_, **__): # properties cannot process parameters
  943. return func
  944. return func_wrapper
  945. except AttributeError:
  946. try:
  947. mod, name = func.rsplit('.', 1)
  948. m = __import__(mod)
  949. for n in mod.split('.')[1:]:
  950. m = getattr(m, n)
  951. func = getattr(m, name)
  952. except (ImportError, AttributeError, ValueError):
  953. raise AttributeError("Callable with name '%s' could neither be retrieved from the passed "
  954. "model nor imported from a module." % func)
  955. return func
  956. def _has_state(self, state, raise_error=False):
  957. found = state in self.states.values()
  958. if not found and raise_error:
  959. msg = 'State %s has not been added to the machine' % (state.name if hasattr(state, 'name') else state)
  960. raise ValueError(msg)
  961. return found
  962. def _process(self, trigger):
  963. # default processing
  964. if not self.has_queue:
  965. if not self._transition_queue:
  966. # if trigger raises an Error, it has to be handled by the Machine.process caller
  967. return trigger()
  968. else:
  969. raise MachineError("Attempt to process events synchronously while transition queue is not empty!")
  970. # process queued events
  971. self._transition_queue.append(trigger)
  972. # another entry in the queue implies a running transition; skip immediate execution
  973. if len(self._transition_queue) > 1:
  974. return True
  975. # execute as long as transition queue is not empty
  976. while self._transition_queue:
  977. try:
  978. self._transition_queue[0]()
  979. self._transition_queue.popleft()
  980. except Exception:
  981. # if a transition raises an exception, clear queue and delegate exception handling
  982. self._transition_queue.clear()
  983. raise
  984. return True
  985. @classmethod
  986. def _identify_callback(cls, name):
  987. # Does the prefix match a known callback?
  988. for callback in itertools.chain(cls.state_cls.dynamic_methods, cls.transition_cls.dynamic_methods):
  989. if name.startswith(callback):
  990. callback_type = callback
  991. break
  992. else:
  993. return None, None
  994. # Extract the target by cutting the string after the type and separator
  995. target = name[len(callback_type) + len(cls.separator):]
  996. # Make sure there is actually a target to avoid index error and enforce _ as a separator
  997. if target == '' or name[len(callback_type)] != cls.separator:
  998. return None, None
  999. return callback_type, target
  1000. def __getattr__(self, name):
  1001. # Machine.__dict__ does not contain double underscore variables.
  1002. # Class variables will be mangled.
  1003. if name.startswith('__'):
  1004. raise AttributeError("'{}' does not exist on <Machine@{}>"
  1005. .format(name, id(self)))
  1006. # Could be a callback
  1007. callback_type, target = self._identify_callback(name)
  1008. if callback_type is not None:
  1009. if callback_type in self.transition_cls.dynamic_methods:
  1010. if target not in self.events:
  1011. raise AttributeError("event '{}' is not registered on <Machine@{}>"
  1012. .format(target, id(self)))
  1013. return partial(self.events[target].add_callback, callback_type)
  1014. elif callback_type in self.state_cls.dynamic_methods:
  1015. state = self.get_state(target)
  1016. return partial(state.add_callback, callback_type[3:])
  1017. # Nothing matched
  1018. raise AttributeError("'{}' does not exist on <Machine@{}>".format(name, id(self)))
  1019. class MachineError(Exception):
  1020. """ MachineError is used for issues related to state transitions and current states.
  1021. For instance, it is raised for invalid transitions or machine configuration issues.
  1022. """
  1023. def __init__(self, value):
  1024. super(MachineError, self).__init__(value)
  1025. self.value = value
  1026. def __str__(self):
  1027. return repr(self.value)