index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
727,779
fysom
Fysom
Wraps the complete finite state machine operations.
class Fysom(object): ''' Wraps the complete finite state machine operations. ''' def __init__(self, cfg={}, initial=None, events=None, callbacks=None, final=None, **kwargs): ''' Construct a Finite State Machine. Arguments: cfg finite state machine specification, a dictionary with keys 'initial', 'events', 'callbacks', 'final' initial initial state events a list of dictionaries (keys: 'name', 'src', 'dst') or a list tuples (event name, source state or states, destination state or states) callbacks a dictionary mapping callback names to functions final a state of the FSM where its is_finished() method returns True Named arguments override configuration dictionary. Example: >>> fsm = Fysom(events=[('tic', 'a', 'b'), ('toc', 'b', 'a')], initial='a') >>> fsm.current 'a' >>> fsm.tic() >>> fsm.current 'b' >>> fsm.toc() >>> fsm.current 'a' ''' if (sys.version_info[0] >= 3): super().__init__(**kwargs) cfg = dict(cfg) # override cfg with named arguments if "events" not in cfg: cfg["events"] = [] if "callbacks" not in cfg: cfg["callbacks"] = {} if initial: cfg["initial"] = initial if final: cfg["final"] = final if events: cfg["events"].extend(list(events)) if callbacks: cfg["callbacks"].update(dict(callbacks)) # convert 3-tuples in the event specification to dicts events_dicts = [] for e in cfg["events"]: if isinstance(e, Mapping): events_dicts.append(e) elif hasattr(e, "__iter__"): name, src, dst = list(e)[:3] events_dicts.append({"name": name, "src": src, "dst": dst}) cfg["events"] = events_dicts self._apply(cfg) def isstate(self, state): ''' Returns if the given state is the current state. ''' return self.current == state is_state = isstate def can(self, event): ''' Returns if the given event be fired in the current machine state. ''' return ( event in self._map and ((self.current in self._map[event]) or WILDCARD in self._map[event]) and not hasattr(self, 'transition')) def cannot(self, event): ''' Returns if the given event cannot be fired in the current state. ''' return not self.can(event) def is_finished(self): ''' Returns if the state machine is in its final state. ''' return self._final and (self.current == self._final) def _apply(self, cfg): ''' Does the heavy lifting of machine construction. More notably: >> Sets up the initial and finals states. >> Sets the event methods and callbacks into the same object namespace. >> Prepares the event to state transitions map. ''' init = cfg['initial'] if 'initial' in cfg else None if self._is_base_string(init): init = {'state': init} self._final = cfg['final'] if 'final' in cfg else None events = cfg['events'] if 'events' in cfg else [] callbacks = cfg['callbacks'] if 'callbacks' in cfg else {} tmap = {} self._map = tmap def add(e): ''' Adds the event into the machine map. ''' if 'src' in e: src = [e['src']] if self._is_base_string( e['src']) else e['src'] else: src = [WILDCARD] if e['name'] not in tmap: tmap[e['name']] = {} for s in src: tmap[e['name']][s] = e['dst'] # Consider initial state as any other state that can have transition from none to # initial value on occurance of startup / init event ( if specified). if init: if 'event' not in init: init['event'] = 'startup' add({'name': init['event'], 'src': 'none', 'dst': init['state']}) for e in events: add(e) # For all the events as present in machine map, construct the event # handler. for name in tmap: setattr(self, name, self._build_event(name)) # For all the callbacks, register them into the current object # namespace. for name in callbacks: setattr(self, name, _weak_callback(callbacks[name])) self.current = 'none' # If initialization need not be deferred, trigger the event for # transition to initial state. if init and 'defer' not in init: getattr(self, init['event'])() def _build_event(self, event): ''' For every event in the state machine, prepares the event handler and registers the same into current object namespace. ''' def fn(*args, **kwargs): if hasattr(self, 'transition'): raise FysomError( "event %s inappropriate because previous transition did not complete" % event) # Check if this event can be triggered in the current state. if not self.can(event): raise FysomError( "event %s inappropriate in current state %s" % (event, self.current)) # On event occurence, source will always be the current state. src = self.current # Finds the destination state, after this event is completed. dst = ((src in self._map[event] and self._map[event][src]) or WILDCARD in self._map[event] and self._map[event][WILDCARD]) if dst == SAME_DST: dst = src # Prepares the object with all the meta data to be passed to # callbacks. class _e_obj(object): pass e = _e_obj() e.fsm, e.event, e.src, e.dst = self, event, src, dst for k in kwargs: setattr(e, k, kwargs[k]) setattr(e, 'args', args) # Try to trigger the before event, unless it gets canceled. if self._before_event(e) is False: raise Canceled( "Cannot trigger event {0} because the onbefore{0} handler returns False".format(e.event)) # Wraps the activities that must constitute a single successful # transaction. if self.current != dst: def _tran(): delattr(self, 'transition') self.current = dst self._enter_state(e) self._change_state(e) self._after_event(e) self.transition = _tran # Hook to perform asynchronous transition. if self._leave_state(e) is not False: self.transition() else: self._reenter_state(e) self._after_event(e) fn.__name__ = str(event) fn.__doc__ = ("Event handler for an {event} event. This event can be " + "fired if the machine is in {states} states.".format( event=event, states=self._map[event].keys())) return fn def _before_event(self, e): ''' Checks to see if the callback is registered before this event can be triggered. ''' for fnname in ['onbefore' + e.event, 'on_before_' + e.event]: if hasattr(self, fnname): return getattr(self, fnname)(e) def _after_event(self, e): ''' Checks to see if the callback is registered for, after this event is completed. ''' for fnname in ['onafter' + e.event, 'on' + e.event, 'on_after_' + e.event, 'on_' + e.event]: if hasattr(self, fnname): return getattr(self, fnname)(e) def _leave_state(self, e): ''' Checks to see if the machine can leave the current state and perform the transition. This is helpful if the asynchronous job needs to be completed before the machine can leave the current state. ''' for fnname in ['onleave' + e.src, 'on_leave_' + e.src]: if hasattr(self, fnname): return getattr(self, fnname)(e) def _enter_state(self, e): ''' Executes the callback for onenter_state_ or on_state_. ''' for fnname in ['onenter' + e.dst, 'on' + e.dst, 'on_enter_' + e.dst, 'on_' + e.dst]: if hasattr(self, fnname): return getattr(self, fnname)(e) def _reenter_state(self, e): ''' Executes the callback for onreenter_state_. This allows callbacks following reflexive transitions (i.e. where src == dst) ''' for fnname in ['onreenter' + e.dst, 'on_reenter_' + e.dst]: if hasattr(self, fnname): return getattr(self, fnname)(e) def _change_state(self, e): ''' A general change state callback. This gets triggered at the time of state transition. ''' for fnname in ['onchangestate', 'on_change_state']: if hasattr(self, fnname): return getattr(self, fnname)(e) def _is_base_string(self, object): # pragma: no cover ''' Returns if the object is an instance of basestring. ''' try: return isinstance(object, basestring) except NameError: return isinstance(object, str) def trigger(self, event, *args, **kwargs): ''' Triggers the given event. The event can be triggered by calling the event handler directly, for ex: fsm.eat() but this method will come in handy if the event is determined dynamically and you have the event name to trigger as a string. ''' if not hasattr(self, event): raise FysomError( "There isn't any event registered as %s" % event) return getattr(self, event)(*args, **kwargs)
(cfg={}, initial=None, events=None, callbacks=None, final=None, **kwargs)
727,780
fysom
__init__
Construct a Finite State Machine. Arguments: cfg finite state machine specification, a dictionary with keys 'initial', 'events', 'callbacks', 'final' initial initial state events a list of dictionaries (keys: 'name', 'src', 'dst') or a list tuples (event name, source state or states, destination state or states) callbacks a dictionary mapping callback names to functions final a state of the FSM where its is_finished() method returns True Named arguments override configuration dictionary. Example: >>> fsm = Fysom(events=[('tic', 'a', 'b'), ('toc', 'b', 'a')], initial='a') >>> fsm.current 'a' >>> fsm.tic() >>> fsm.current 'b' >>> fsm.toc() >>> fsm.current 'a'
def __init__(self, cfg={}, initial=None, events=None, callbacks=None, final=None, **kwargs): ''' Construct a Finite State Machine. Arguments: cfg finite state machine specification, a dictionary with keys 'initial', 'events', 'callbacks', 'final' initial initial state events a list of dictionaries (keys: 'name', 'src', 'dst') or a list tuples (event name, source state or states, destination state or states) callbacks a dictionary mapping callback names to functions final a state of the FSM where its is_finished() method returns True Named arguments override configuration dictionary. Example: >>> fsm = Fysom(events=[('tic', 'a', 'b'), ('toc', 'b', 'a')], initial='a') >>> fsm.current 'a' >>> fsm.tic() >>> fsm.current 'b' >>> fsm.toc() >>> fsm.current 'a' ''' if (sys.version_info[0] >= 3): super().__init__(**kwargs) cfg = dict(cfg) # override cfg with named arguments if "events" not in cfg: cfg["events"] = [] if "callbacks" not in cfg: cfg["callbacks"] = {} if initial: cfg["initial"] = initial if final: cfg["final"] = final if events: cfg["events"].extend(list(events)) if callbacks: cfg["callbacks"].update(dict(callbacks)) # convert 3-tuples in the event specification to dicts events_dicts = [] for e in cfg["events"]: if isinstance(e, Mapping): events_dicts.append(e) elif hasattr(e, "__iter__"): name, src, dst = list(e)[:3] events_dicts.append({"name": name, "src": src, "dst": dst}) cfg["events"] = events_dicts self._apply(cfg)
(self, cfg={}, initial=None, events=None, callbacks=None, final=None, **kwargs)
727,781
fysom
_after_event
Checks to see if the callback is registered for, after this event is completed.
def _after_event(self, e): ''' Checks to see if the callback is registered for, after this event is completed. ''' for fnname in ['onafter' + e.event, 'on' + e.event, 'on_after_' + e.event, 'on_' + e.event]: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,782
fysom
_apply
Does the heavy lifting of machine construction. More notably: >> Sets up the initial and finals states. >> Sets the event methods and callbacks into the same object namespace. >> Prepares the event to state transitions map.
def _apply(self, cfg): ''' Does the heavy lifting of machine construction. More notably: >> Sets up the initial and finals states. >> Sets the event methods and callbacks into the same object namespace. >> Prepares the event to state transitions map. ''' init = cfg['initial'] if 'initial' in cfg else None if self._is_base_string(init): init = {'state': init} self._final = cfg['final'] if 'final' in cfg else None events = cfg['events'] if 'events' in cfg else [] callbacks = cfg['callbacks'] if 'callbacks' in cfg else {} tmap = {} self._map = tmap def add(e): ''' Adds the event into the machine map. ''' if 'src' in e: src = [e['src']] if self._is_base_string( e['src']) else e['src'] else: src = [WILDCARD] if e['name'] not in tmap: tmap[e['name']] = {} for s in src: tmap[e['name']][s] = e['dst'] # Consider initial state as any other state that can have transition from none to # initial value on occurance of startup / init event ( if specified). if init: if 'event' not in init: init['event'] = 'startup' add({'name': init['event'], 'src': 'none', 'dst': init['state']}) for e in events: add(e) # For all the events as present in machine map, construct the event # handler. for name in tmap: setattr(self, name, self._build_event(name)) # For all the callbacks, register them into the current object # namespace. for name in callbacks: setattr(self, name, _weak_callback(callbacks[name])) self.current = 'none' # If initialization need not be deferred, trigger the event for # transition to initial state. if init and 'defer' not in init: getattr(self, init['event'])()
(self, cfg)
727,783
fysom
_before_event
Checks to see if the callback is registered before this event can be triggered.
def _before_event(self, e): ''' Checks to see if the callback is registered before this event can be triggered. ''' for fnname in ['onbefore' + e.event, 'on_before_' + e.event]: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,784
fysom
_build_event
For every event in the state machine, prepares the event handler and registers the same into current object namespace.
def _build_event(self, event): ''' For every event in the state machine, prepares the event handler and registers the same into current object namespace. ''' def fn(*args, **kwargs): if hasattr(self, 'transition'): raise FysomError( "event %s inappropriate because previous transition did not complete" % event) # Check if this event can be triggered in the current state. if not self.can(event): raise FysomError( "event %s inappropriate in current state %s" % (event, self.current)) # On event occurence, source will always be the current state. src = self.current # Finds the destination state, after this event is completed. dst = ((src in self._map[event] and self._map[event][src]) or WILDCARD in self._map[event] and self._map[event][WILDCARD]) if dst == SAME_DST: dst = src # Prepares the object with all the meta data to be passed to # callbacks. class _e_obj(object): pass e = _e_obj() e.fsm, e.event, e.src, e.dst = self, event, src, dst for k in kwargs: setattr(e, k, kwargs[k]) setattr(e, 'args', args) # Try to trigger the before event, unless it gets canceled. if self._before_event(e) is False: raise Canceled( "Cannot trigger event {0} because the onbefore{0} handler returns False".format(e.event)) # Wraps the activities that must constitute a single successful # transaction. if self.current != dst: def _tran(): delattr(self, 'transition') self.current = dst self._enter_state(e) self._change_state(e) self._after_event(e) self.transition = _tran # Hook to perform asynchronous transition. if self._leave_state(e) is not False: self.transition() else: self._reenter_state(e) self._after_event(e) fn.__name__ = str(event) fn.__doc__ = ("Event handler for an {event} event. This event can be " + "fired if the machine is in {states} states.".format( event=event, states=self._map[event].keys())) return fn
(self, event)
727,785
fysom
_change_state
A general change state callback. This gets triggered at the time of state transition.
def _change_state(self, e): ''' A general change state callback. This gets triggered at the time of state transition. ''' for fnname in ['onchangestate', 'on_change_state']: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,786
fysom
_enter_state
Executes the callback for onenter_state_ or on_state_.
def _enter_state(self, e): ''' Executes the callback for onenter_state_ or on_state_. ''' for fnname in ['onenter' + e.dst, 'on' + e.dst, 'on_enter_' + e.dst, 'on_' + e.dst]: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,787
fysom
_is_base_string
Returns if the object is an instance of basestring.
def _is_base_string(self, object): # pragma: no cover ''' Returns if the object is an instance of basestring. ''' try: return isinstance(object, basestring) except NameError: return isinstance(object, str)
(self, object)
727,788
fysom
_leave_state
Checks to see if the machine can leave the current state and perform the transition. This is helpful if the asynchronous job needs to be completed before the machine can leave the current state.
def _leave_state(self, e): ''' Checks to see if the machine can leave the current state and perform the transition. This is helpful if the asynchronous job needs to be completed before the machine can leave the current state. ''' for fnname in ['onleave' + e.src, 'on_leave_' + e.src]: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,789
fysom
_reenter_state
Executes the callback for onreenter_state_. This allows callbacks following reflexive transitions (i.e. where src == dst)
def _reenter_state(self, e): ''' Executes the callback for onreenter_state_. This allows callbacks following reflexive transitions (i.e. where src == dst) ''' for fnname in ['onreenter' + e.dst, 'on_reenter_' + e.dst]: if hasattr(self, fnname): return getattr(self, fnname)(e)
(self, e)
727,790
fysom
can
Returns if the given event be fired in the current machine state.
def can(self, event): ''' Returns if the given event be fired in the current machine state. ''' return ( event in self._map and ((self.current in self._map[event]) or WILDCARD in self._map[event]) and not hasattr(self, 'transition'))
(self, event)
727,791
fysom
cannot
Returns if the given event cannot be fired in the current state.
def cannot(self, event): ''' Returns if the given event cannot be fired in the current state. ''' return not self.can(event)
(self, event)
727,792
fysom
is_finished
Returns if the state machine is in its final state.
def is_finished(self): ''' Returns if the state machine is in its final state. ''' return self._final and (self.current == self._final)
(self)
727,793
fysom
isstate
Returns if the given state is the current state.
def isstate(self, state): ''' Returns if the given state is the current state. ''' return self.current == state
(self, state)
727,795
fysom
trigger
Triggers the given event. The event can be triggered by calling the event handler directly, for ex: fsm.eat() but this method will come in handy if the event is determined dynamically and you have the event name to trigger as a string.
def trigger(self, event, *args, **kwargs): ''' Triggers the given event. The event can be triggered by calling the event handler directly, for ex: fsm.eat() but this method will come in handy if the event is determined dynamically and you have the event name to trigger as a string. ''' if not hasattr(self, event): raise FysomError( "There isn't any event registered as %s" % event) return getattr(self, event)(*args, **kwargs)
(self, event, *args, **kwargs)
727,796
fysom
FysomError
Raised whenever an unexpected event gets triggered. Optionally the event object can be attached to the exception in case of sharing event data.
class FysomError(Exception): ''' Raised whenever an unexpected event gets triggered. Optionally the event object can be attached to the exception in case of sharing event data. ''' def __init__(self, msg, event=None): super(FysomError, self).__init__(msg) self.event = event
(msg, event=None)
727,798
fysom
FysomGlobal
Target to be used as global machine.
class FysomGlobal(object): ''' Target to be used as global machine. ''' def __init__(self, cfg={}, initial=None, events=None, callbacks=None, final=None, state_field=None, **kwargs): ''' Construct a Global Finite State Machine. Takes same arguments as Fysom and an additional state_field to specify which field holds the state to be processed. Difference with Fysom: 1. Initial state will only be automatically triggered for class derived with FysomGlobalMixin. 2. Conditions and conditional transition are implemented. 3. When an event/transition is canceled, the event object will be attached to the raised Canceled exception. By doing this, additional information can be passed through the exception. Example: class Model(FysomGlobalMixin, object): GSM = FysomGlobal( events=[('warn', 'green', 'yellow'), { 'name': 'panic', 'src': ['green', 'yellow'], 'dst': 'red', 'cond': [ # can be function object or method name 'is_angry', # by default target is "True" {True: 'is_very_angry', 'else': 'yellow'} ] }, ('calm', 'red', 'yellow'), ('clear', 'yellow', 'green')], initial='green', final='red', state_field='state' ) def __init__(self): self.state = None super(Model, self).__init__() def is_angry(self, event): return True def is_very_angry(self, event): return False >>> obj = Model() >>> obj.current 'green' >>> obj.warn() >>> obj.is_state('yellow') True >>> obj.panic() >>> obj.current 'yellow' >>> obj.is_finished() False ''' if sys.version_info[0] >= 3: super().__init__(**kwargs) cfg = dict(cfg) # state_field is required for global machine if not state_field: raise FysomError('state_field required for global machine') self.state_field = state_field if "events" not in cfg: cfg["events"] = [] if "callbacks" not in cfg: cfg["callbacks"] = {} if initial: cfg['initial'] = initial if events: cfg["events"].extend(list(events)) if callbacks: cfg["callbacks"].update(dict(callbacks)) if final: cfg["final"] = final # convert 3-tuples in the event specification to dicts events_dicts = [] for e in cfg["events"]: if isinstance(e, Mapping): events_dicts.append(e) elif hasattr(e, "__iter__"): name, src, dst = list(e)[:3] events_dicts.append({"name": name, "src": src, "dst": dst}) cfg["events"] = events_dicts self._map = {} # different with Fysom's _map attribute self._callbacks = {} self._initial = None self._final = None self._apply(cfg) def _apply(self, cfg): def add(e): if 'src' in e: src = [e['src']] if self._is_base_string( e['src']) else e['src'] else: src = [WILDCARD] _e = {'src': set(src), 'dst': e['dst']} conditions = e.get('cond') if conditions: _e['cond'] = _c = [] if self._is_base_string(conditions) or callable(conditions): _c.append({True: conditions}) else: for cond in conditions: if self._is_base_string(cond): _c.append({True: cond}) else: _c.append(cond) self._map[e['name']] = _e initial = cfg['initial'] if 'initial' in cfg else None if self._is_base_string(initial): initial = {'state': initial} if initial: if 'event' not in initial: initial['event'] = 'startup' self._initial = initial add({'name': initial['event'], 'src': 'none', 'dst': initial['state']}) if 'final' in cfg: self._final = cfg['final'] for e in cfg['events']: add(e) for event in self._map: setattr(self, event, self._build_event(event)) for name, callback in cfg['callbacks'].items(): self._callbacks[name] = _weak_callback(callback) def _build_event(self, event): def fn(obj, *args, **kwargs): if not self.can(obj, event): raise FysomError( 'event %s inappropriate in current state %s' % (event, self.current(obj))) # Prepare the event object with all the meta data to pas through. # On event occurrence, source will always be the current state. e = self._e_obj() e.fsm, e.obj, e.event, e.src, e.dst = ( self, obj, event, self.current(obj), self._map[event]['dst']) setattr(e, 'args', args) setattr(e, 'kwargs', kwargs) for k, v in kwargs.items(): setattr(e, k, v) # check conditions first, event dst may change during # checking conditions for c in self._map[event].get('cond', ()): target = True in c cond = c[target] _c_r = self._check_condition(obj, cond, target, e) if not _c_r: if 'else' in c: e.dst = c['else'] break else: raise Canceled( 'Cannot trigger event {0} because the {1} ' 'condition not returns {2}'.format( event, cond, target), e ) # try to trigger the before event, unless it gets cancelled. if self._before_event(obj, e) is False: raise Canceled( 'Cannot trigger event {0} because the onbefore{0} ' 'handler returns False'.format(event), e) # wraps the activities that must constitute a single transaction if self.current(obj) != e.dst: def _trans(): delattr(obj, 'transition') setattr(obj, self.state_field, e.dst) self._enter_state(obj, e) self._change_state(obj, e) self._after_event(obj, e) obj.transition = _trans # Hook to perform asynchronous transition if self._leave_state(obj, e) is not False: obj.transition() else: self._reenter_state(obj, e) self._after_event(obj, e) fn.__name__ = str(event) fn.__doc__ = ( "Event handler for an {event} event. This event can be " "fired if the machine is in {states} states.".format( event=event, states=self._map[event]['src'])) return fn class _e_obj(object): pass @staticmethod def _is_base_string(object): # pragma: no cover try: return isinstance(object, basestring) # noqa except NameError: return isinstance(object, str) # noqa def _do_callbacks(self, obj, callbacks, *args, **kwargs): for cb in callbacks: if cb in self._callbacks: return self._callbacks[cb](*args, **kwargs) if hasattr(obj, cb): return getattr(obj, cb)(*args, **kwargs) def _check_condition(self, obj, func, target, e): if callable(func): return func(e) is target return self._do_callbacks(obj, [func], e) is target def _before_event(self, obj, e): callbacks = ['onbefore' + e.event, 'on_before_' + e.event] return self._do_callbacks(obj, callbacks, e) def _after_event(self, obj, e): callbacks = ['onafter' + e.event, 'on' + e.event, 'on_after_' + e.event, 'on_' + e.event] return self._do_callbacks(obj, callbacks, e) def _leave_state(self, obj, e): callbacks = ['onleave' + e.src, 'on_leave_' + e.src] return self._do_callbacks(obj, callbacks, e) def _enter_state(self, obj, e): callbacks = ['onenter' + e.dst, 'on' + e.dst, 'on_enter_' + e.dst, 'on_' + e.dst] return self._do_callbacks(obj, callbacks, e) def _reenter_state(self, obj, e): callbacks = ['onreenter' + e.dst, 'on_reenter_' + e.dst] return self._do_callbacks(obj, callbacks, e) def _change_state(self, obj, e): callbacks = ['onchangestate', 'on_change_state'] return self._do_callbacks(obj, callbacks, e) def current(self, obj): return getattr(obj, self.state_field) or 'none' def isstate(self, obj, state): return self.current(obj) == state is_state = isstate def can(self, obj, event): if event not in self._map or hasattr(obj, 'transition'): return False src = self._map[event]['src'] return self.current(obj) in src or WILDCARD in src def cannot(self, obj, event): return not self.can(obj, event) def is_finished(self, obj): return self._final and (self.current(obj) == self._final) def trigger(self, obj, event, *args, **kwargs): if not hasattr(self, event): raise FysomError( "There isn't any event registered as %s" % event) return getattr(self, event)(obj, *args, **kwargs)
(cfg={}, initial=None, events=None, callbacks=None, final=None, state_field=None, **kwargs)
727,799
fysom
__init__
Construct a Global Finite State Machine. Takes same arguments as Fysom and an additional state_field to specify which field holds the state to be processed. Difference with Fysom: 1. Initial state will only be automatically triggered for class derived with FysomGlobalMixin. 2. Conditions and conditional transition are implemented. 3. When an event/transition is canceled, the event object will be attached to the raised Canceled exception. By doing this, additional information can be passed through the exception. Example: class Model(FysomGlobalMixin, object): GSM = FysomGlobal( events=[('warn', 'green', 'yellow'), { 'name': 'panic', 'src': ['green', 'yellow'], 'dst': 'red', 'cond': [ # can be function object or method name 'is_angry', # by default target is "True" {True: 'is_very_angry', 'else': 'yellow'} ] }, ('calm', 'red', 'yellow'), ('clear', 'yellow', 'green')], initial='green', final='red', state_field='state' ) def __init__(self): self.state = None super(Model, self).__init__() def is_angry(self, event): return True def is_very_angry(self, event): return False >>> obj = Model() >>> obj.current 'green' >>> obj.warn() >>> obj.is_state('yellow') True >>> obj.panic() >>> obj.current 'yellow' >>> obj.is_finished() False
def __init__(self, cfg={}, initial=None, events=None, callbacks=None, final=None, state_field=None, **kwargs): ''' Construct a Global Finite State Machine. Takes same arguments as Fysom and an additional state_field to specify which field holds the state to be processed. Difference with Fysom: 1. Initial state will only be automatically triggered for class derived with FysomGlobalMixin. 2. Conditions and conditional transition are implemented. 3. When an event/transition is canceled, the event object will be attached to the raised Canceled exception. By doing this, additional information can be passed through the exception. Example: class Model(FysomGlobalMixin, object): GSM = FysomGlobal( events=[('warn', 'green', 'yellow'), { 'name': 'panic', 'src': ['green', 'yellow'], 'dst': 'red', 'cond': [ # can be function object or method name 'is_angry', # by default target is "True" {True: 'is_very_angry', 'else': 'yellow'} ] }, ('calm', 'red', 'yellow'), ('clear', 'yellow', 'green')], initial='green', final='red', state_field='state' ) def __init__(self): self.state = None super(Model, self).__init__() def is_angry(self, event): return True def is_very_angry(self, event): return False >>> obj = Model() >>> obj.current 'green' >>> obj.warn() >>> obj.is_state('yellow') True >>> obj.panic() >>> obj.current 'yellow' >>> obj.is_finished() False ''' if sys.version_info[0] >= 3: super().__init__(**kwargs) cfg = dict(cfg) # state_field is required for global machine if not state_field: raise FysomError('state_field required for global machine') self.state_field = state_field if "events" not in cfg: cfg["events"] = [] if "callbacks" not in cfg: cfg["callbacks"] = {} if initial: cfg['initial'] = initial if events: cfg["events"].extend(list(events)) if callbacks: cfg["callbacks"].update(dict(callbacks)) if final: cfg["final"] = final # convert 3-tuples in the event specification to dicts events_dicts = [] for e in cfg["events"]: if isinstance(e, Mapping): events_dicts.append(e) elif hasattr(e, "__iter__"): name, src, dst = list(e)[:3] events_dicts.append({"name": name, "src": src, "dst": dst}) cfg["events"] = events_dicts self._map = {} # different with Fysom's _map attribute self._callbacks = {} self._initial = None self._final = None self._apply(cfg)
(self, cfg={}, initial=None, events=None, callbacks=None, final=None, state_field=None, **kwargs)
727,800
fysom
_after_event
null
def _after_event(self, obj, e): callbacks = ['onafter' + e.event, 'on' + e.event, 'on_after_' + e.event, 'on_' + e.event] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,801
fysom
_apply
null
def _apply(self, cfg): def add(e): if 'src' in e: src = [e['src']] if self._is_base_string( e['src']) else e['src'] else: src = [WILDCARD] _e = {'src': set(src), 'dst': e['dst']} conditions = e.get('cond') if conditions: _e['cond'] = _c = [] if self._is_base_string(conditions) or callable(conditions): _c.append({True: conditions}) else: for cond in conditions: if self._is_base_string(cond): _c.append({True: cond}) else: _c.append(cond) self._map[e['name']] = _e initial = cfg['initial'] if 'initial' in cfg else None if self._is_base_string(initial): initial = {'state': initial} if initial: if 'event' not in initial: initial['event'] = 'startup' self._initial = initial add({'name': initial['event'], 'src': 'none', 'dst': initial['state']}) if 'final' in cfg: self._final = cfg['final'] for e in cfg['events']: add(e) for event in self._map: setattr(self, event, self._build_event(event)) for name, callback in cfg['callbacks'].items(): self._callbacks[name] = _weak_callback(callback)
(self, cfg)
727,802
fysom
_before_event
null
def _before_event(self, obj, e): callbacks = ['onbefore' + e.event, 'on_before_' + e.event] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,803
fysom
_build_event
null
def _build_event(self, event): def fn(obj, *args, **kwargs): if not self.can(obj, event): raise FysomError( 'event %s inappropriate in current state %s' % (event, self.current(obj))) # Prepare the event object with all the meta data to pas through. # On event occurrence, source will always be the current state. e = self._e_obj() e.fsm, e.obj, e.event, e.src, e.dst = ( self, obj, event, self.current(obj), self._map[event]['dst']) setattr(e, 'args', args) setattr(e, 'kwargs', kwargs) for k, v in kwargs.items(): setattr(e, k, v) # check conditions first, event dst may change during # checking conditions for c in self._map[event].get('cond', ()): target = True in c cond = c[target] _c_r = self._check_condition(obj, cond, target, e) if not _c_r: if 'else' in c: e.dst = c['else'] break else: raise Canceled( 'Cannot trigger event {0} because the {1} ' 'condition not returns {2}'.format( event, cond, target), e ) # try to trigger the before event, unless it gets cancelled. if self._before_event(obj, e) is False: raise Canceled( 'Cannot trigger event {0} because the onbefore{0} ' 'handler returns False'.format(event), e) # wraps the activities that must constitute a single transaction if self.current(obj) != e.dst: def _trans(): delattr(obj, 'transition') setattr(obj, self.state_field, e.dst) self._enter_state(obj, e) self._change_state(obj, e) self._after_event(obj, e) obj.transition = _trans # Hook to perform asynchronous transition if self._leave_state(obj, e) is not False: obj.transition() else: self._reenter_state(obj, e) self._after_event(obj, e) fn.__name__ = str(event) fn.__doc__ = ( "Event handler for an {event} event. This event can be " "fired if the machine is in {states} states.".format( event=event, states=self._map[event]['src'])) return fn
(self, event)
727,804
fysom
_change_state
null
def _change_state(self, obj, e): callbacks = ['onchangestate', 'on_change_state'] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,805
fysom
_check_condition
null
def _check_condition(self, obj, func, target, e): if callable(func): return func(e) is target return self._do_callbacks(obj, [func], e) is target
(self, obj, func, target, e)
727,806
fysom
_do_callbacks
null
def _do_callbacks(self, obj, callbacks, *args, **kwargs): for cb in callbacks: if cb in self._callbacks: return self._callbacks[cb](*args, **kwargs) if hasattr(obj, cb): return getattr(obj, cb)(*args, **kwargs)
(self, obj, callbacks, *args, **kwargs)
727,807
fysom
_enter_state
null
def _enter_state(self, obj, e): callbacks = ['onenter' + e.dst, 'on' + e.dst, 'on_enter_' + e.dst, 'on_' + e.dst] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,808
fysom
_is_base_string
null
@staticmethod def _is_base_string(object): # pragma: no cover try: return isinstance(object, basestring) # noqa except NameError: return isinstance(object, str) # noqa
(object)
727,809
fysom
_leave_state
null
def _leave_state(self, obj, e): callbacks = ['onleave' + e.src, 'on_leave_' + e.src] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,810
fysom
_reenter_state
null
def _reenter_state(self, obj, e): callbacks = ['onreenter' + e.dst, 'on_reenter_' + e.dst] return self._do_callbacks(obj, callbacks, e)
(self, obj, e)
727,811
fysom
can
null
def can(self, obj, event): if event not in self._map or hasattr(obj, 'transition'): return False src = self._map[event]['src'] return self.current(obj) in src or WILDCARD in src
(self, obj, event)
727,812
fysom
cannot
null
def cannot(self, obj, event): return not self.can(obj, event)
(self, obj, event)
727,813
fysom
current
null
def current(self, obj): return getattr(obj, self.state_field) or 'none'
(self, obj)
727,814
fysom
is_finished
null
def is_finished(self, obj): return self._final and (self.current(obj) == self._final)
(self, obj)
727,815
fysom
isstate
null
def isstate(self, obj, state): return self.current(obj) == state
(self, obj, state)
727,817
fysom
trigger
null
def trigger(self, obj, event, *args, **kwargs): if not hasattr(self, event): raise FysomError( "There isn't any event registered as %s" % event) return getattr(self, event)(obj, *args, **kwargs)
(self, obj, event, *args, **kwargs)
727,818
fysom
FysomGlobalMixin
null
class FysomGlobalMixin(object): GSM = None # global state machine instance, override this def __init__(self, *args, **kwargs): super(FysomGlobalMixin, self).__init__(*args, **kwargs) if self.is_state('none'): _initial = self.GSM._initial if _initial and not _initial.get('defer'): self.trigger(_initial['event']) def __getattribute__(self, attr): ''' Proxy public event methods to global machine if available. ''' try: return super(FysomGlobalMixin, self).__getattribute__(attr) except AttributeError as err: if not attr.startswith('_'): gsm_attr = getattr(self.GSM, attr) if callable(gsm_attr): return functools.partial(gsm_attr, self) raise # pragma: no cover @property def current(self): ''' Simulate the behavior of Fysom's "current" attribute. ''' return self.GSM.current(self) @current.setter def current(self, state): setattr(self, self.GSM.state_field, state)
(*args, **kwargs)
727,819
fysom
__getattribute__
Proxy public event methods to global machine if available.
def __getattribute__(self, attr): ''' Proxy public event methods to global machine if available. ''' try: return super(FysomGlobalMixin, self).__getattribute__(attr) except AttributeError as err: if not attr.startswith('_'): gsm_attr = getattr(self.GSM, attr) if callable(gsm_attr): return functools.partial(gsm_attr, self) raise # pragma: no cover
(self, attr)
727,820
fysom
__init__
null
def __init__(self, *args, **kwargs): super(FysomGlobalMixin, self).__init__(*args, **kwargs) if self.is_state('none'): _initial = self.GSM._initial if _initial and not _initial.get('defer'): self.trigger(_initial['event'])
(self, *args, **kwargs)
727,831
fysom
_weak_callback
Store a weak reference to a callback or method.
def _weak_callback(func): ''' Store a weak reference to a callback or method. ''' if isinstance(func, types.MethodType): # Don't hold a reference to the object, otherwise we might create # a cycle. # Reference: http://stackoverflow.com/a/6975682 # Tell coveralls to not cover this if block, as the Python 2.x case # doesn't test the 3.x code and vice versa. if sys.version_info[0] < 3: # pragma: no cover # Python 2.x case obj_ref = weakref.ref(func.im_self) func_ref = weakref.ref(func.im_func) else: # pragma: no cover # Python 3.x case obj_ref = weakref.ref(func.__self__) func_ref = weakref.ref(func.__func__) func = None def _callback(*args, **kwargs): obj = obj_ref() func = func_ref() if (obj is None) or (func is None): return return func(obj, *args, **kwargs) return _callback else: # We should be safe enough holding callback functions ourselves. return func
(func)
727,836
nibe_mqtt.config
Config
null
class Config: def __init__(self): self._data = None def load(self, config_file: Path) -> dict: assert config_file.is_file(), f"{config_file} should be a file" with config_file.open("r", encoding="utf-8") as fh: self._data = schema(yaml.safe_load(fh)) return self._data def get(self): assert self._data is not None, "Not yet loaded" return self._data
()
727,837
nibe_mqtt.config
__init__
null
def __init__(self): self._data = None
(self)
727,838
nibe_mqtt.config
get
null
def get(self): assert self._data is not None, "Not yet loaded" return self._data
(self)
727,839
nibe_mqtt.config
load
null
def load(self, config_file: Path) -> dict: assert config_file.is_file(), f"{config_file} should be a file" with config_file.open("r", encoding="utf-8") as fh: self._data = schema(yaml.safe_load(fh)) return self._data
(self, config_file: pathlib.Path) -> dict
727,841
captionizer.captionizer
caption_from_path
null
def caption_from_path(file_path, base_path, class_token=None, token=None): # Prefer OrderedDict - key order in regular dict is only guaranteed # from Python 3.7 onward. tokens = OrderedDict([('S', token), ('C', class_token)]) return generic_captions_from_path(file_path, base_path, tokens)
(file_path, base_path, class_token=None, token=None)
727,843
captionizer.finder
find_images
null
def find_images(root_folder, glob_pattern="**/*.*"): return list(glob.glob(f'{root_folder}{os.path.sep}{glob_pattern}', recursive=True))
(root_folder, glob_pattern='**/*.*')
727,845
captionizer.captionizer
generic_captions_from_path
null
def generic_captions_from_path(file_path, base_path, tokens): rel_path = os.path.relpath(file_path, base_path) parent_path = os.path.dirname(rel_path) caption = 'broken caption' if parent_path == '': caption = token_caption(tokens, rel_path) else: caption = path_caption(rel_path, tokens) return caption
(file_path, base_path, tokens)
727,846
typeapi.typehint
AnnotatedTypeHint
Represents the `Annotated` type hint.
class AnnotatedTypeHint(TypeHint): """Represents the `Annotated` type hint.""" @property def args(self) -> Tuple[Any, ...]: return (self._args[0],) def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": assert len(args) == 1 new_hint = Annotated[args + (self._args[1:])] # type: ignore return AnnotatedTypeHint(new_hint) def __len__(self) -> int: return 1 @property def type(self) -> Any: """ Returns the wrapped type of the annotation. It's common to wrap the result in a `TypeHint` to recursively introspect the wrapped type. >>> TypeHint(Annotated[int, "foobar"]).type <class 'int'> """ return self._args[0] @property def metadata(self) -> Tuple[Any, ...]: """ Returns the metadata, i.e. all the parameters after the wrapped type. >>> TypeHint(Annotated[int, "foobar"]).metadata ('foobar',) """ return self._args[1:]
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,847
typeapi.typehint
__eq__
null
def __eq__(self, other: object) -> bool: if type(self) != type(other): return False assert isinstance(other, TypeHint) return (self.hint, self.origin, self.args, self.parameters) == ( other.hint, other.origin, other.args, other.parameters, )
(self, other: object) -> bool
727,848
typeapi.typehint
__getitem__
null
def __getitem__(self, index: "int | slice") -> "TypeHint | List[TypeHint]": if isinstance(index, int): try: return TypeHint(self.args[index]) except IndexError: raise IndexError(f"TypeHint index {index} out of range [0..{len(self.args)}[") else: return [TypeHint(x) for x in self.args[index]]
(self, index: int | slice) -> Union[typeapi.typehint.TypeHint, List[typeapi.typehint.TypeHint]]
727,849
typeapi.typehint
__init__
null
def __init__(self, hint: object, source: "Any | None" = None) -> None: self._hint = hint self._origin = get_type_hint_origin_or_none(hint) self._args = get_type_hint_args(hint) self._parameters = get_type_hint_parameters(hint) self._source = source
(self, hint: object, source: Optional[Any] = None) -> NoneType
727,850
typeapi.typehint
__iter__
null
def __iter__(self) -> Iterator["TypeHint"]: for i in range(len(self.args)): yield self[i]
(self) -> Iterator[typeapi.typehint.TypeHint]
727,852
typeapi.typehint
__repr__
null
def __repr__(self) -> str: return f"TypeHint({type_repr(self._hint)})"
(self) -> str
727,853
typeapi.typehint
_copy_with_args
null
def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": assert len(args) == 1 new_hint = Annotated[args + (self._args[1:])] # type: ignore return AnnotatedTypeHint(new_hint)
(self, args: Tuple[Any, ...]) -> typeapi.typehint.TypeHint
727,854
typeapi.typehint
evaluate
Evaluate forward references in the type hint using the given *context*. This method supports evaluating forward references that use PEP585 and PEP604 syntax even in older versions of Python that do not support the PEPs. :param context: An object that supports `__getitem__()` to retrieve a value by name. If this is not specified, the globals of the `__module__` of the type hint's source :attr:`source` is used instead. If no source exists, a :class:`RuntimeError` is raised.
def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> "TypeHint": """ Evaluate forward references in the type hint using the given *context*. This method supports evaluating forward references that use PEP585 and PEP604 syntax even in older versions of Python that do not support the PEPs. :param context: An object that supports `__getitem__()` to retrieve a value by name. If this is not specified, the globals of the `__module__` of the type hint's source :attr:`source` is used instead. If no source exists, a :class:`RuntimeError` is raised. """ if context is None: context = self.get_context() if self.origin is not None and self.args: args = tuple(TypeHint(x).evaluate(context).hint for x in self.args) return self._copy_with_args(args) else: return self
(self, context: Optional[typeapi.utils.HasGetitem[str, Any]] = None) -> typeapi.typehint.TypeHint
727,855
typeapi.typehint
get_context
Return the context for this type hint in which forward references must be evaluated. The context is derived from the `source` attribute, which can be either a `ModuleType`, `Mapping` or `type`. In case of a `type`, the context is composed of the class scope (to resolve class-level members) and the scope of the module that contains the type (looked up in `sys.modules`). Raises RuntimeError: If `source` is `None` or has not one of the three supported types.
def get_context(self) -> HasGetitem[str, Any]: """Return the context for this type hint in which forward references must be evaluated. The context is derived from the `source` attribute, which can be either a `ModuleType`, `Mapping` or `type`. In case of a `type`, the context is composed of the class scope (to resolve class-level members) and the scope of the module that contains the type (looked up in `sys.modules`). Raises RuntimeError: If `source` is `None` or has not one of the three supported types. """ if self.source is None: raise RuntimeError( f"Missing context for {self}.evaluate(), the type hint has no `.source` " "to which we could fall back to. Specify the `context` argument or make sure that the type " "hint's `.source` is set." ) if isinstance(self.source, ModuleType): return vars(self.source) if isinstance(self.source, Mapping): return self.source if isinstance(self.source, type): return ChainMap( cast(MutableMapping[str, Any], vars(self.source)), cast(MutableMapping[str, Any], vars(sys.modules[self.source.__module__])), ) raise RuntimeError(f"Unable to determine TypeHint.source context from source={self.source!r}")
(self) -> typeapi.utils.HasGetitem[str, typing.Any]
727,856
typeapi.typehint
parameterize
Replace references to the type variables in the keys of *parameter_map* with the type hints of the associated values. :param parameter_map: A dictionary that maps :class:`TypeVar` to other type hints.
def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": """ Replace references to the type variables in the keys of *parameter_map* with the type hints of the associated values. :param parameter_map: A dictionary that maps :class:`TypeVar` to other type hints. """ if self.origin is not None and self.args: args = tuple(TypeHint(x).parameterize(parameter_map).hint for x in self.args) return self._copy_with_args(args) else: return self
(self, parameter_map: Mapping[object, Any]) -> typeapi.typehint.TypeHint
727,857
typeapi.typehint
ClassTypeHint
Represents a real, possibly parameterized, type. For example `int`, `list`, `list[int]` or `list[T]`.
class ClassTypeHint(TypeHint): """Represents a real, possibly parameterized, type. For example `int`, `list`, `list[int]` or `list[T]`.""" def __init__(self, hint: object, source: "Any | None" = None) -> None: super().__init__(hint, source) assert isinstance(self.hint, type) or isinstance(self.origin, type), ( "ClassTypeHint must be initialized from a real type or a generic that points to a real type. " f'Got "{self.hint!r}" with origin "{self.origin}"' ) def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": if self.type is Generic: # type: ignore[comparison-overlap] return self return super().parameterize(parameter_map) @property def type(self) -> type: """Returns the concrepte type.""" if isinstance(self.origin, type): return self.origin if isinstance(self.hint, type): return self.hint assert False, "ClassTypeHint not initialized from a real type or a generic that points to a real type." @property def bases(self) -> "Tuple[Any, ...]": """ Return the bases of the classes' types. If the type is a generic, the bases of the generic's origin are returned in their parameterized form (e.g. `Generic[T]` instead of `Generic` is returned). """ return get_type_hint_original_bases(self.type) or self.type.__bases__ def get_parameter_map(self) -> Dict[Any, Any]: """ Returns a dictionary that maps generic parameters to their values. >>> TypeHint(List[int]).type <class 'list'> >>> TypeHint(List[int]).args (<class 'int'>,) # NOTE(@niklas): This is a bug for built-in types, but it's not that big of a deal because we don't # usually need to recursively expand forward references in these types. >>> TypeHint(List[int]).parameters () >>> TypeHint(List[int]).get_parameter_map() {} >>> T = TypeVar("T") >>> class A(Generic[T]): pass >>> TypeHint(A[int]).get_parameter_map() {~T: <class 'int'>} """ if not self.args: return {} # We need to look at the parameters of the original, un-parameterized type. That's why we can't # use self.parameters. return dict(zip(TypeHint(self.type).parameters, self.args)) def recurse_bases( self, order: Literal["dfs", "bfs"] = "bfs" ) -> Generator["ClassTypeHint", Union[Literal["skip"], None], None]: """ Iterate over all base classes of this type hint, and continues recursively. The iteration order is determined by the *order* parameter, which can be either depth-first or breadh-first. If the generator receives the string `"skip"` from the caller, it will skip the bases of the last yielded type. """ # Find the item type in the base classes of the collection type. bases = deque([self]) while bases: current = bases.popleft() if not isinstance(current, ClassTypeHint): raise RuntimeError( f"Expected to find a ClassTypeHint in the base classes of {self!r}, found {current!r} instead." ) response = yield current if response == "skip": continue current_bases = cast( List[ClassTypeHint], [TypeHint(x, current.type).evaluate().parameterize(current.get_parameter_map()) for x in current.bases], ) if order == "bfs": bases.extend(current_bases) elif order == "dfs": bases.extendleft(reversed(current_bases)) else: raise ValueError(f"Invalid order {order!r}")
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,860
typeapi.typehint
__init__
null
def __init__(self, hint: object, source: "Any | None" = None) -> None: super().__init__(hint, source) assert isinstance(self.hint, type) or isinstance(self.origin, type), ( "ClassTypeHint must be initialized from a real type or a generic that points to a real type. " f'Got "{self.hint!r}" with origin "{self.origin}"' )
(self, hint: object, source: Optional[Any] = None) -> NoneType
727,862
typeapi.typehint
__len__
null
def __len__(self) -> int: return len(self.args)
(self) -> int
727,864
typeapi.typehint
_copy_with_args
Internal. Create a copy of this type hint with updated type arguments.
def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": """ Internal. Create a copy of this type hint with updated type arguments. """ generic = get_subscriptable_type_hint_from_origin(self.origin) try: new_hint = generic[args] except TypeError as exc: raise TypeError(f"{type_repr(generic)}: {exc}") return TypeHint(new_hint)
(self, args: Tuple[Any, ...]) -> typeapi.typehint.TypeHint
727,867
typeapi.typehint
get_parameter_map
Returns a dictionary that maps generic parameters to their values. >>> TypeHint(List[int]).type <class 'list'> >>> TypeHint(List[int]).args (<class 'int'>,) # NOTE(@niklas): This is a bug for built-in types, but it's not that big of a deal because we don't # usually need to recursively expand forward references in these types. >>> TypeHint(List[int]).parameters () >>> TypeHint(List[int]).get_parameter_map() {} >>> T = TypeVar("T") >>> class A(Generic[T]): pass >>> TypeHint(A[int]).get_parameter_map() {~T: <class 'int'>}
def get_parameter_map(self) -> Dict[Any, Any]: """ Returns a dictionary that maps generic parameters to their values. >>> TypeHint(List[int]).type <class 'list'> >>> TypeHint(List[int]).args (<class 'int'>,) # NOTE(@niklas): This is a bug for built-in types, but it's not that big of a deal because we don't # usually need to recursively expand forward references in these types. >>> TypeHint(List[int]).parameters () >>> TypeHint(List[int]).get_parameter_map() {} >>> T = TypeVar("T") >>> class A(Generic[T]): pass >>> TypeHint(A[int]).get_parameter_map() {~T: <class 'int'>} """ if not self.args: return {} # We need to look at the parameters of the original, un-parameterized type. That's why we can't # use self.parameters. return dict(zip(TypeHint(self.type).parameters, self.args))
(self) -> Dict[Any, Any]
727,868
typeapi.typehint
parameterize
null
def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": if self.type is Generic: # type: ignore[comparison-overlap] return self return super().parameterize(parameter_map)
(self, parameter_map: Mapping[object, Any]) -> typeapi.typehint.TypeHint
727,869
typeapi.typehint
recurse_bases
Iterate over all base classes of this type hint, and continues recursively. The iteration order is determined by the *order* parameter, which can be either depth-first or breadh-first. If the generator receives the string `"skip"` from the caller, it will skip the bases of the last yielded type.
def recurse_bases( self, order: Literal["dfs", "bfs"] = "bfs" ) -> Generator["ClassTypeHint", Union[Literal["skip"], None], None]: """ Iterate over all base classes of this type hint, and continues recursively. The iteration order is determined by the *order* parameter, which can be either depth-first or breadh-first. If the generator receives the string `"skip"` from the caller, it will skip the bases of the last yielded type. """ # Find the item type in the base classes of the collection type. bases = deque([self]) while bases: current = bases.popleft() if not isinstance(current, ClassTypeHint): raise RuntimeError( f"Expected to find a ClassTypeHint in the base classes of {self!r}, found {current!r} instead." ) response = yield current if response == "skip": continue current_bases = cast( List[ClassTypeHint], [TypeHint(x, current.type).evaluate().parameterize(current.get_parameter_map()) for x in current.bases], ) if order == "bfs": bases.extend(current_bases) elif order == "dfs": bases.extendleft(reversed(current_bases)) else: raise ValueError(f"Invalid order {order!r}")
(self, order: Literal['dfs', 'bfs'] = 'bfs') -> Generator[typeapi.typehint.ClassTypeHint, Optional[Literal['skip']], NoneType]
727,870
typeapi.typehint
ForwardRefTypeHint
Represents a forward reference, i.e. a string in the type annotation or an explicit `ForwardRef`.
class ForwardRefTypeHint(TypeHint): """Represents a forward reference, i.e. a string in the type annotation or an explicit `ForwardRef`.""" def __init__(self, hint: object, source: "Any | None") -> None: super().__init__(hint, source) if isinstance(self._hint, str): self._forward_ref = ForwardRef(self._hint) elif isinstance(self._hint, ForwardRef): self._forward_ref = self._hint else: raise TypeError( f"ForwardRefTypeHint must be initialized from a typing.ForwardRef or str. Got: {type(self._hint)!r}" ) def parameterize(self, parameter_map: Mapping[object, Any]) -> TypeHint: raise RuntimeError( "ForwardRef cannot be parameterized. Ensure that your type hint is fully " "evaluated before parameterization." ) def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> TypeHint: from .future.fake import FakeProvider if context is None: context = self.get_context() hint = FakeProvider(context).execute(self.expr).evaluate() return TypeHint(hint).evaluate(context) @property def hint(self) -> "ForwardRef | str": """Returns the original type hint.""" return self._hint # type: ignore @property def ref(self) -> ForwardRef: """Same as `hint`, but returns it as a `ForwardRef` always.""" return self._forward_ref @property def expr(self) -> str: """ Returns the expression of the forward reference. >>> TypeHint(ForwardRef("Foobar")).expr 'Foobar' >>> TypeHint(TypeHint(List["Foobar"]).args[0]).expr 'Foobar' """ return self._forward_ref.__forward_arg__
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,873
typeapi.typehint
__init__
null
def __init__(self, hint: object, source: "Any | None") -> None: super().__init__(hint, source) if isinstance(self._hint, str): self._forward_ref = ForwardRef(self._hint) elif isinstance(self._hint, ForwardRef): self._forward_ref = self._hint else: raise TypeError( f"ForwardRefTypeHint must be initialized from a typing.ForwardRef or str. Got: {type(self._hint)!r}" )
(self, hint: object, source: Optional[Any]) -> NoneType
727,878
typeapi.typehint
evaluate
null
def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> TypeHint: from .future.fake import FakeProvider if context is None: context = self.get_context() hint = FakeProvider(context).execute(self.expr).evaluate() return TypeHint(hint).evaluate(context)
(self, context: Optional[typeapi.utils.HasGetitem[str, Any]] = None) -> typeapi.typehint.TypeHint
727,880
typeapi.typehint
parameterize
null
def parameterize(self, parameter_map: Mapping[object, Any]) -> TypeHint: raise RuntimeError( "ForwardRef cannot be parameterized. Ensure that your type hint is fully " "evaluated before parameterization." )
(self, parameter_map: Mapping[object, Any]) -> typeapi.typehint.TypeHint
727,881
typeapi.typehint
LiteralTypeHint
Represents a literal type hint, e.g. `Literal["a", 42]`.
class LiteralTypeHint(TypeHint): """Represents a literal type hint, e.g. `Literal["a", 42]`.""" @property def args(self) -> Tuple[Any, ...]: return () def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": return self def __len__(self) -> int: return 0 @property def values(self) -> Tuple[Any, ...]: """ Returns the values of the literal. >>> TypeHint(Literal["a", 42]).values ('a', 42) """ return self._args
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,891
typeapi.typehint
parameterize
null
def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": return self
(self, parameter_map: Mapping[object, Any]) -> typeapi.typehint.TypeHint
727,892
typeapi.typehint
TupleTypeHint
A special class to represent a type hint for a parameterized tuple. This class does not represent a plain tuple type without parameterization.
class TupleTypeHint(ClassTypeHint): """ A special class to represent a type hint for a parameterized tuple. This class does not represent a plain tuple type without parameterization. """ def __init__(self, hint: object, source: "Any | None") -> None: super().__init__(hint, source) if self._args == ((),): self._args = () elif self._args == () and self._hint == tuple: raise ValueError("TupleTypeHint can only represent a parameterized tuple.") if ... in self._args: assert self._args[-1] == ..., "Tuple Ellipsis not as last arg" assert len(self._args) == 2, "Tuple with Ellipsis has more than two args" self._repeated = True self._args = self._args[:-1] else: self._repeated = False def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": if self._repeated: args = args + (...,) return super()._copy_with_args(args) @property def type(self) -> type: return tuple @property def repeated(self) -> bool: """ Returns `True` if the Tuple is of arbitrary length, but only of one type. """ return self._repeated
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,895
typeapi.typehint
__init__
null
def __init__(self, hint: object, source: "Any | None") -> None: super().__init__(hint, source) if self._args == ((),): self._args = () elif self._args == () and self._hint == tuple: raise ValueError("TupleTypeHint can only represent a parameterized tuple.") if ... in self._args: assert self._args[-1] == ..., "Tuple Ellipsis not as last arg" assert len(self._args) == 2, "Tuple with Ellipsis has more than two args" self._repeated = True self._args = self._args[:-1] else: self._repeated = False
(self, hint: object, source: Optional[Any]) -> NoneType
727,899
typeapi.typehint
_copy_with_args
null
def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": if self._repeated: args = args + (...,) return super()._copy_with_args(args)
(self, args: Tuple[Any, ...]) -> typeapi.typehint.TypeHint
727,905
typeapi.typehint
TypeHint
Base class that provides an object-oriented interface to a Python type hint.
class TypeHint(object, metaclass=_TypeHintMeta): """ Base class that provides an object-oriented interface to a Python type hint. """ def __init__(self, hint: object, source: "Any | None" = None) -> None: self._hint = hint self._origin = get_type_hint_origin_or_none(hint) self._args = get_type_hint_args(hint) self._parameters = get_type_hint_parameters(hint) self._source = source def __repr__(self) -> str: return f"TypeHint({type_repr(self._hint)})" @property def hint(self) -> object: """ The original type hint. """ return self._hint @property def origin(self) -> "object | None": """ The original type behind a type hint (e.g. the `Generic.__origin__`). For example, for :class:`typing.List`, it is `list`. For :class:`typing.Sequence`, it is :class:`collections.abc.Sequence`. """ return self._origin @property def args(self) -> Tuple[Any, ...]: """ Type hint arguments are the values passed into type hint subscripts, e.g. in `Union[int, str]`, the arguments are `(int, str)`. We only return arguments that are expected to be types or other type hints. For example, `Literal["foo", 0]` has an empty tuple for its `args`, and instead the values can be retrievd using :attr:`LiteralTypeHint.valuse`. """ return self._args @property def parameters(self) -> Tuple[Any, ...]: """ The parameters of a type hint is basically :attr:`args` but filtered for #typing.TypeVar objects. """ return self._parameters @property def source(self) -> "Any | None": """ The object from which on which the type hint was found, for example a class or a function. """ return self._source def __eq__(self, other: object) -> bool: if type(self) != type(other): return False assert isinstance(other, TypeHint) return (self.hint, self.origin, self.args, self.parameters) == ( other.hint, other.origin, other.args, other.parameters, ) def __iter__(self) -> Iterator["TypeHint"]: for i in range(len(self.args)): yield self[i] def __len__(self) -> int: return len(self.args) @overload def __getitem__(self, __index: int) -> "TypeHint": ... @overload def __getitem__(self, __slice: slice) -> List["TypeHint"]: ... def __getitem__(self, index: "int | slice") -> "TypeHint | List[TypeHint]": if isinstance(index, int): try: return TypeHint(self.args[index]) except IndexError: raise IndexError(f"TypeHint index {index} out of range [0..{len(self.args)}[") else: return [TypeHint(x) for x in self.args[index]] def _copy_with_args(self, args: "Tuple[Any, ...]") -> "TypeHint": """ Internal. Create a copy of this type hint with updated type arguments. """ generic = get_subscriptable_type_hint_from_origin(self.origin) try: new_hint = generic[args] except TypeError as exc: raise TypeError(f"{type_repr(generic)}: {exc}") return TypeHint(new_hint) def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": """ Replace references to the type variables in the keys of *parameter_map* with the type hints of the associated values. :param parameter_map: A dictionary that maps :class:`TypeVar` to other type hints. """ if self.origin is not None and self.args: args = tuple(TypeHint(x).parameterize(parameter_map).hint for x in self.args) return self._copy_with_args(args) else: return self def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> "TypeHint": """ Evaluate forward references in the type hint using the given *context*. This method supports evaluating forward references that use PEP585 and PEP604 syntax even in older versions of Python that do not support the PEPs. :param context: An object that supports `__getitem__()` to retrieve a value by name. If this is not specified, the globals of the `__module__` of the type hint's source :attr:`source` is used instead. If no source exists, a :class:`RuntimeError` is raised. """ if context is None: context = self.get_context() if self.origin is not None and self.args: args = tuple(TypeHint(x).evaluate(context).hint for x in self.args) return self._copy_with_args(args) else: return self def get_context(self) -> HasGetitem[str, Any]: """Return the context for this type hint in which forward references must be evaluated. The context is derived from the `source` attribute, which can be either a `ModuleType`, `Mapping` or `type`. In case of a `type`, the context is composed of the class scope (to resolve class-level members) and the scope of the module that contains the type (looked up in `sys.modules`). Raises RuntimeError: If `source` is `None` or has not one of the three supported types. """ if self.source is None: raise RuntimeError( f"Missing context for {self}.evaluate(), the type hint has no `.source` " "to which we could fall back to. Specify the `context` argument or make sure that the type " "hint's `.source` is set." ) if isinstance(self.source, ModuleType): return vars(self.source) if isinstance(self.source, Mapping): return self.source if isinstance(self.source, type): return ChainMap( cast(MutableMapping[str, Any], vars(self.source)), cast(MutableMapping[str, Any], vars(sys.modules[self.source.__module__])), ) raise RuntimeError(f"Unable to determine TypeHint.source context from source={self.source!r}")
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,916
typeapi.typehint
TypeVarTypeHint
Represents a `TypeVar` type hint.
class TypeVarTypeHint(TypeHint): """Represents a `TypeVar` type hint.""" @property def hint(self) -> TypeVar: assert isinstance(self._hint, TypeVar) return self._hint def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": return TypeHint(parameter_map.get(self.hint, self.hint)) def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> TypeHint: return self @property def name(self) -> str: """ Returns the name of the type variable. >>> TypeHint(TypeVar("T")).name 'T' """ return self.hint.__name__ @property def covariant(self) -> bool: """ Returns whether the TypeVar is covariant. >>> TypeHint(TypeVar("T")).covariant False >>> TypeHint(TypeVar("T", covariant=True)).covariant True """ return self.hint.__covariant__ @property def contravariant(self) -> bool: """ Returns whether the TypeVar is contravariant. >>> TypeHint(TypeVar("T")).contravariant False >>> TypeHint(TypeVar("T", contravariant=True)).contravariant True """ return self.hint.__contravariant__ @property def constraints(self) -> "Tuple[Any, ...]": """ Returns the constraints of the TypeVar. >>> TypeHint(TypeVar("T", int, str)).constraints (<class 'int'>, <class 'str'>) """ return self.hint.__constraints__ @property def bound(self) -> Any: """ Returns what the TypeVar is bound to. >>> TypeHint(TypeVar("T", bound=str)).bound <class 'str'> """ return self.hint.__bound__
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,924
typeapi.typehint
evaluate
null
def evaluate(self, context: "HasGetitem[str, Any] | None" = None) -> TypeHint: return self
(self, context: Optional[typeapi.utils.HasGetitem[str, Any]] = None) -> typeapi.typehint.TypeHint
727,926
typeapi.typehint
parameterize
null
def parameterize(self, parameter_map: Mapping[object, Any]) -> "TypeHint": return TypeHint(parameter_map.get(self.hint, self.hint))
(self, parameter_map: Mapping[object, Any]) -> typeapi.typehint.TypeHint
727,927
typeapi.utils
TypedDictProtocol
A protocol that describes #typing.TypedDict values (which are actually instances of the #typing._TypedDictMeta metaclass). Use #is_typed_dict() to check if a hint is matches this protocol.
class TypedDictProtocol(Protocol): """A protocol that describes #typing.TypedDict values (which are actually instances of the #typing._TypedDictMeta metaclass). Use #is_typed_dict() to check if a hint is matches this protocol.""" __annotations__: Dict[str, Any] __required_keys__: Set[str] __optional_keys__: Set[str] __total__: bool
(*args, **kwargs)
727,929
typeapi.typehint
UnionTypeHint
Represents a union of types, e.g. `typing.Union[A, B]` or `A | B`.
class UnionTypeHint(TypeHint): """Represents a union of types, e.g. `typing.Union[A, B]` or `A | B`.""" def has_none_type(self) -> bool: return NoneType in self._args def without_none_type(self) -> TypeHint: args = tuple(x for x in self._args if x is not NoneType) if len(args) == 1: return TypeHint(args[0]) else: return self._copy_with_args(args)
(hint: object, source: 'Any | None' = None) -> 'TypeHint'
727,939
typeapi.typehint
has_none_type
null
def has_none_type(self) -> bool: return NoneType in self._args
(self) -> bool
727,941
typeapi.typehint
without_none_type
null
def without_none_type(self) -> TypeHint: args = tuple(x for x in self._args if x is not NoneType) if len(args) == 1: return TypeHint(args[0]) else: return self._copy_with_args(args)
(self) -> typeapi.typehint.TypeHint
727,943
typeapi.utils
get_annotations
Like #typing.get_type_hints(), but always includes extras. This is important when we want to inspect #typing.Annotated hints (without extras the annotations are removed). In Python 3.10 and onwards, this is an alias for #inspect.get_annotations() with `eval_str=True`. If *include_bases* is set to `True`, annotations from base classes are taken into account as well. This function will take into account the locals and globals accessible through the frame associated with a function or type by the #scoped() decorator.
def get_annotations( obj: Union[Callable[..., Any], ModuleType, type], include_bases: bool = False, globalns: Optional[Dict[str, Any]] = None, localns: Optional[Dict[str, Any]] = None, eval_str: bool = True, ) -> Dict[str, Any]: """Like #typing.get_type_hints(), but always includes extras. This is important when we want to inspect #typing.Annotated hints (without extras the annotations are removed). In Python 3.10 and onwards, this is an alias for #inspect.get_annotations() with `eval_str=True`. If *include_bases* is set to `True`, annotations from base classes are taken into account as well. This function will take into account the locals and globals accessible through the frame associated with a function or type by the #scoped() decorator.""" if hasattr(obj, "__typeapi_frame__"): frame: FrameType = obj.__typeapi_frame__ # type: ignore[union-attr] globalns = frame.f_globals localns = frame.f_locals del frame elif hasattr(obj, "__module__"): module = sys.modules.get(obj.__module__) if module is None: warnings.warn( f"sys.modules[{obj.__module__!r}] does not exist, type hint resolution context for object of type " f"{type(obj).__name__!r} will not be available.", UserWarning, ) else: assert hasattr(module, "__dict__"), module globalns = vars(module) from collections import ChainMap from .typehint import TypeHint def eval_callback(hint_expr: str, globals: Any, locals: Any) -> Any: chainmap = ChainMap(locals or {}, globals or {}) if isinstance(obj, type): chainmap = chainmap.new_child(cast(MutableMapping[str, Any], vars(obj))) hint = TypeHint(hint_expr, chainmap) return hint.evaluate().hint annotations = _inspect_get_annotations(obj, globals=globalns, locals=localns, eval_str=eval_str, eval=eval_callback) if isinstance(obj, type) and include_bases: annotations = {} for base in obj.__mro__: base_annotations = _inspect_get_annotations( base, globals=globalns, locals=localns, eval_str=eval_str, eval=eval_callback ) annotations.update({k: v for k, v in base_annotations.items() if k not in annotations}) return annotations
(obj: Union[Callable[..., Any], module, type], include_bases: bool = False, globalns: Optional[Dict[str, Any]] = None, localns: Optional[Dict[str, Any]] = None, eval_str: bool = True) -> Dict[str, Any]
727,944
typeapi.utils
is_typed_dict
Returns: `True` if *hint* is a #typing.TypedDict. !!! note Typed dictionaries are actually just type objects. This means #typeapi.of() will represent them as #typeapi.models.Type.
def is_typed_dict(hint: Any) -> TypeGuard[TypedDictProtocol]: """ Returns: `True` if *hint* is a #typing.TypedDict. !!! note Typed dictionaries are actually just type objects. This means #typeapi.of() will represent them as #typeapi.models.Type. """ import typing import typing_extensions for m in (typing, typing_extensions): if hasattr(m, "_TypedDictMeta") and isinstance(hint, m._TypedDictMeta): # type: ignore[attr-defined] return True return False
(hint: Any) -> TypeGuard[typeapi.utils.TypedDictProtocol]
727,945
typeapi.utils
type_repr
#typing._type_repr() stolen from Python 3.8.
def type_repr(obj: Any) -> str: """#typing._type_repr() stolen from Python 3.8.""" if (getattr(obj, "__module__", None) or getattr(type(obj), "__module__", None)) in TYPING_MODULE_NAMES or hasattr( obj, "__args__" ): # NOTE(NiklasRosenstein): In Python 3.6, List[int] is actually a "type" subclass so we can't # rely on the fall through on the below. return repr(obj) if isinstance(obj, type): if obj.__module__ == "builtins": return obj.__qualname__ return f"{obj.__module__}.{obj.__qualname__}" if obj is ...: return "..." if isinstance(obj, FunctionType): return obj.__name__ return repr(obj)
(obj: Any) -> str
727,948
builtins
dict
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
dict[str, str]
null
727,949
mod_wsgi_van.router
Router
Router(base_path: str = '/var/www', venv_name: str = '.venv', wsgi_dir: str = 'wsgi', module_name: str = 'app', object_name: str = 'app', update_interval: float = 1.0)
class Router: base_path: str = "/var/www" venv_name: str = ".venv" wsgi_dir: str = "wsgi" module_name: str = "app" object_name: str = "app" update_interval: float = 1.0 def __post_init__(self) -> None: self.servers: dict[str, Server] = {} self.stop_watcher = threading.Event() self.watcher = threading.Thread( target=self.poll_server_paths, daemon=True, ) self.watcher.start() atexit.register(self.shutdown) def shutdown(self): self.stop_watcher.set() self.watcher.join() def get_version(self, path: pathlib.Path) -> typing.Any: # Monitor the vhost's WSGI directory wsgi_path = path / self.wsgi_dir # Follow symlink changes hard_path = wsgi_path.resolve(strict=True) # Allow touching to reload like mod_wsgi return os.stat(hard_path).st_mtime def poll_server_paths(self): # Update servers when their path changes while not self.stop_watcher.wait(self.update_interval): for server in list(self.servers.values()): try: # Reload modules after a deploy server.update(self.get_version(server.path)) except Exception as e: # Purge deleted servers server.log(e) server.log("Closing") del self.servers[server.host_name] def get_server_path(self, host_name: str) -> pathlib.Path: return pathlib.Path(self.base_path, host_name) def get_venv_paths(self, path: pathlib.Path) -> list[pathlib.Path]: venv_path = path / self.venv_name return list(venv_path.glob("lib/python*/site-packages")) def get_server(self, environ: Environ) -> Server: host_name = environ["HTTP_HOST"] # Lazy load and cache WSGI servers on request if host_name not in self.servers: path = self.get_server_path(host_name) server = Server( host_name=host_name, script_name=environ["mod_wsgi.script_name"], path=path, venv_paths=self.get_venv_paths(path), wsgi_dir=self.wsgi_dir, module_name=self.module_name, object_name=self.object_name, version=self.get_version(path), ) server.load() self.servers[host_name] = server return self.servers[host_name] def application(self, environ: Environ, start_response: StartResponse) -> Response: start_time = time.perf_counter() server = self.get_server(environ) with server.time("serve", start_time): # Drain the generator to time the response yield from server.serve(environ, start_response)
(base_path: str = '/var/www', venv_name: str = '.venv', wsgi_dir: str = 'wsgi', module_name: str = 'app', object_name: str = 'app', update_interval: float = 1.0) -> None
727,950
mod_wsgi_van.router
__eq__
null
import atexit import dataclasses import os import pathlib import threading import time import typing from .server import Server, Environ, StartResponse, Response @dataclasses.dataclass class Router: base_path: str = "/var/www" venv_name: str = ".venv" wsgi_dir: str = "wsgi" module_name: str = "app" object_name: str = "app" update_interval: float = 1.0 def __post_init__(self) -> None: self.servers: dict[str, Server] = {} self.stop_watcher = threading.Event() self.watcher = threading.Thread( target=self.poll_server_paths, daemon=True, ) self.watcher.start() atexit.register(self.shutdown) def shutdown(self): self.stop_watcher.set() self.watcher.join() def get_version(self, path: pathlib.Path) -> typing.Any: # Monitor the vhost's WSGI directory wsgi_path = path / self.wsgi_dir # Follow symlink changes hard_path = wsgi_path.resolve(strict=True) # Allow touching to reload like mod_wsgi return os.stat(hard_path).st_mtime def poll_server_paths(self): # Update servers when their path changes while not self.stop_watcher.wait(self.update_interval): for server in list(self.servers.values()): try: # Reload modules after a deploy server.update(self.get_version(server.path)) except Exception as e: # Purge deleted servers server.log(e) server.log("Closing") del self.servers[server.host_name] def get_server_path(self, host_name: str) -> pathlib.Path: return pathlib.Path(self.base_path, host_name) def get_venv_paths(self, path: pathlib.Path) -> list[pathlib.Path]: venv_path = path / self.venv_name return list(venv_path.glob("lib/python*/site-packages")) def get_server(self, environ: Environ) -> Server: host_name = environ["HTTP_HOST"] # Lazy load and cache WSGI servers on request if host_name not in self.servers: path = self.get_server_path(host_name) server = Server( host_name=host_name, script_name=environ["mod_wsgi.script_name"], path=path, venv_paths=self.get_venv_paths(path), wsgi_dir=self.wsgi_dir, module_name=self.module_name, object_name=self.object_name, version=self.get_version(path), ) server.load() self.servers[host_name] = server return self.servers[host_name] def application(self, environ: Environ, start_response: StartResponse) -> Response: start_time = time.perf_counter() server = self.get_server(environ) with server.time("serve", start_time): # Drain the generator to time the response yield from server.serve(environ, start_response)
(self, other)
727,952
mod_wsgi_van.router
__post_init__
null
def __post_init__(self) -> None: self.servers: dict[str, Server] = {} self.stop_watcher = threading.Event() self.watcher = threading.Thread( target=self.poll_server_paths, daemon=True, ) self.watcher.start() atexit.register(self.shutdown)
(self) -> NoneType
727,954
mod_wsgi_van.router
application
null
def application(self, environ: Environ, start_response: StartResponse) -> Response: start_time = time.perf_counter() server = self.get_server(environ) with server.time("serve", start_time): # Drain the generator to time the response yield from server.serve(environ, start_response)
(self, environ: dict[str, str], start_response: Callable) -> Generator
727,955
mod_wsgi_van.router
get_server
null
def get_server(self, environ: Environ) -> Server: host_name = environ["HTTP_HOST"] # Lazy load and cache WSGI servers on request if host_name not in self.servers: path = self.get_server_path(host_name) server = Server( host_name=host_name, script_name=environ["mod_wsgi.script_name"], path=path, venv_paths=self.get_venv_paths(path), wsgi_dir=self.wsgi_dir, module_name=self.module_name, object_name=self.object_name, version=self.get_version(path), ) server.load() self.servers[host_name] = server return self.servers[host_name]
(self, environ: dict[str, str]) -> mod_wsgi_van.server.Server
727,956
mod_wsgi_van.router
get_server_path
null
def get_server_path(self, host_name: str) -> pathlib.Path: return pathlib.Path(self.base_path, host_name)
(self, host_name: str) -> pathlib.Path
727,957
mod_wsgi_van.router
get_venv_paths
null
def get_venv_paths(self, path: pathlib.Path) -> list[pathlib.Path]: venv_path = path / self.venv_name return list(venv_path.glob("lib/python*/site-packages"))
(self, path: pathlib.Path) -> list[pathlib.Path]
727,958
mod_wsgi_van.router
get_version
null
def get_version(self, path: pathlib.Path) -> typing.Any: # Monitor the vhost's WSGI directory wsgi_path = path / self.wsgi_dir # Follow symlink changes hard_path = wsgi_path.resolve(strict=True) # Allow touching to reload like mod_wsgi return os.stat(hard_path).st_mtime
(self, path: pathlib.Path) -> Any
727,959
mod_wsgi_van.router
poll_server_paths
null
def poll_server_paths(self): # Update servers when their path changes while not self.stop_watcher.wait(self.update_interval): for server in list(self.servers.values()): try: # Reload modules after a deploy server.update(self.get_version(server.path)) except Exception as e: # Purge deleted servers server.log(e) server.log("Closing") del self.servers[server.host_name]
(self)
727,960
mod_wsgi_van.router
shutdown
null
def shutdown(self): self.stop_watcher.set() self.watcher.join()
(self)
727,961
mod_wsgi_van.server
Server
Server(host_name: str, script_name: str, path: pathlib.Path, venv_paths: list[pathlib.Path], wsgi_dir: str, module_name: str, object_name: str, version: Any, import_cache: dict[str, module] = <factory>)
class Server: host_name: str script_name: str path: pathlib.Path venv_paths: list[pathlib.Path] wsgi_dir: str module_name: str object_name: str version: typing.Any import_cache: dict[str, types.ModuleType] = dataclasses.field(default_factory=dict) def load(self) -> None: # Load one module at a time since sys is global self.log("Loading") with self.time("load"), self.environment(): self.module = importlib.import_module(self.module_name) self.handler: Handler = getattr(self.module, self.object_name) def update(self, version: typing.Any) -> None: if self.version != version: # Clear import cache and reload self.import_cache = {} self.load() self.version = version def serve(self, environ: Environ, start_response: typing.Callable) -> Response: with self.environment(): yield from self.handler(environ, start_response) @contextlib.contextmanager def environment(self): # Load cached imports global_modules = set(sys.modules.keys()) sys.modules.update(self.import_cache) # Prefix the import path with the server and venv for path in self.venv_paths: sys.path.insert(0, str(path)) sys.path.insert(0, str(self.path / self.wsgi_dir)) try: yield None finally: # Reset the path sys.path.pop(0) for _ in self.venv_paths: sys.path.pop(0) # Unload imports into a cache self.import_cache = { name: sys.modules.pop(name) for name in set(sys.modules.keys()) - global_modules } def log(self, message) -> None: print(f"(wsgi:{self.script_name}:{self.host_name}): {message}") @contextlib.contextmanager def time(self, event: str, start_time: float | None = None): start_time = start_time or time.perf_counter() try: yield None finally: end_time = time.perf_counter() timing = end_time - start_time self.log(f"[{timing:.3g} s] {event}")
(host_name: str, script_name: str, path: pathlib.Path, venv_paths: list[pathlib.Path], wsgi_dir: str, module_name: str, object_name: str, version: Any, import_cache: dict[str, module] = <factory>) -> None
727,962
mod_wsgi_van.server
__eq__
null
import contextlib import dataclasses import importlib import pathlib import sys import time import types import typing Environ = dict[str, str] Response = typing.Generator StartResponse = typing.Callable Handler = typing.Callable[[Environ, StartResponse], Response] @dataclasses.dataclass class Server: host_name: str script_name: str path: pathlib.Path venv_paths: list[pathlib.Path] wsgi_dir: str module_name: str object_name: str version: typing.Any import_cache: dict[str, types.ModuleType] = dataclasses.field(default_factory=dict) def load(self) -> None: # Load one module at a time since sys is global self.log("Loading") with self.time("load"), self.environment(): self.module = importlib.import_module(self.module_name) self.handler: Handler = getattr(self.module, self.object_name) def update(self, version: typing.Any) -> None: if self.version != version: # Clear import cache and reload self.import_cache = {} self.load() self.version = version def serve(self, environ: Environ, start_response: typing.Callable) -> Response: with self.environment(): yield from self.handler(environ, start_response) @contextlib.contextmanager def environment(self): # Load cached imports global_modules = set(sys.modules.keys()) sys.modules.update(self.import_cache) # Prefix the import path with the server and venv for path in self.venv_paths: sys.path.insert(0, str(path)) sys.path.insert(0, str(self.path / self.wsgi_dir)) try: yield None finally: # Reset the path sys.path.pop(0) for _ in self.venv_paths: sys.path.pop(0) # Unload imports into a cache self.import_cache = { name: sys.modules.pop(name) for name in set(sys.modules.keys()) - global_modules } def log(self, message) -> None: print(f"(wsgi:{self.script_name}:{self.host_name}): {message}") @contextlib.contextmanager def time(self, event: str, start_time: float | None = None): start_time = start_time or time.perf_counter() try: yield None finally: end_time = time.perf_counter() timing = end_time - start_time self.log(f"[{timing:.3g} s] {event}")
(self, other)
727,966
mod_wsgi_van.server
load
null
def load(self) -> None: # Load one module at a time since sys is global self.log("Loading") with self.time("load"), self.environment(): self.module = importlib.import_module(self.module_name) self.handler: Handler = getattr(self.module, self.object_name)
(self) -> NoneType
727,967
mod_wsgi_van.server
log
null
def log(self, message) -> None: print(f"(wsgi:{self.script_name}:{self.host_name}): {message}")
(self, message) -> NoneType
727,968
mod_wsgi_van.server
serve
null
def serve(self, environ: Environ, start_response: typing.Callable) -> Response: with self.environment(): yield from self.handler(environ, start_response)
(self, environ: dict[str, str], start_response: Callable) -> Generator