snakeoil.dependant_methods module¶
Metaclass to inject dependencies into method calls.
Roughly, if you have 3 methods- that must be ran in the order of start, transfer, finish, this metaclass enables you to force it such that if finish is called first, start, than transfer, finally finish will be invoked transparently.
Methods involved should all require just self
.
The main usage for this code is to enable long chains of steps to be broken down into individual methods, and the consuming api not being required to know the proper order of invocation for that api unless they want to.
Most consumers of this metaclass wind up making a finish
method the final step-
via that, consuming api’s only requirement is knowing that if they invoke finish
all necessary steps will be ran in the correct order.
Example usage:
>>> from snakeoil.dependant_methods import ForcedDepends
>>> class foo(metaclass=ForcedDepends):
... stage_depends = {"finish": ("do_step1", "do_step2"),
... "do_step1":"start", "do_step2": "start"}
...
... def finish(self):
... print("finish invoked")
... return True
... def do_step1(self):
... print("running step1")
... return True
... def do_step2(self):
... print("running step2")
... return True
... def start(self):
... print("starting")
... return True
>>>
>>> obj = foo()
>>> result = obj.finish()
starting
running step1
running step2
finish invoked
>>> result = obj.finish()
>>> # note, no output since finish has already been ran.
- class snakeoil.dependant_methods.ForcedDepends(name, bases, d)[source]¶
Bases:
type
Metaclass forcing methods to run in a certain order.
Dependencies are controlled by the existance of a stage_depends dict in the class namespace. Its keys are method names, values are either a string (name of preceeding method), or list/tuple (proceeding methods).
- Variables:
stage_depends – mapping of stage -> stages that must be ran first Dependant stages can either be a string (single stage), or a tuple- multiple stages, required in the order the’re specified
__stage_step_callback__ – callback accepting a single arg, the phase that just ran. This method/callback is primarily useful for getting raw notification of stages that have just completed- whether for notifying a user, or for debugging.
__set_stage_state__ – method accepting a sequence; the stages completed for this instance are set to that sequence. This should be used with extreme care; primarily useful for resuming a sequence of stages midway through.