Last active
December 18, 2015 01:49
-
-
Save witsch/5707055 to your computer and use it in GitHub Desktop.
metaclass prototype for collecting https://github.com/tomster/ezjail steps & stages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from operator import attrgetter | |
def counter(): | |
count = 0 | |
while True: | |
yield count | |
count += 1 | |
class Step(object): | |
def __init__(self): | |
self.name = None | |
self.id = counter() | |
def __call__(self): | |
return 'call "%s"!' % self.name | |
class CustomStep(Step): | |
def __init__(self, name, func): | |
super(CustomStep, self).__init__() | |
self.name = name | |
self.func = func | |
def __call__(self): | |
return self.func(self) | |
def step(func): | |
return CustomStep(func.func_name, func) | |
class MetaStage(type): | |
def __init__(cls, name, bases, attrs): | |
steps = [] | |
for n, step in attrs.items(): | |
if isinstance(step, Step): | |
step.name = n | |
steps.append(step) | |
cls.steps = sorted(steps, key=attrgetter('id')) | |
super(MetaStage, cls).__init__(name, bases, attrs) | |
class Stage(object): | |
__metaclass__ = MetaStage | |
# now that the package is done, the user can define her stage... | |
class MyStage(Stage): | |
@step | |
def foo(self): | |
return "don't foo me!" | |
hurz = Step() | |
blah = Step() | |
@step | |
def bar(self): | |
return "let's go to the bar" | |
assert [s.name for s in MyStage().steps] == ['foo', 'hurz', 'blah', 'bar'] | |
assert [s() for s in MyStage().steps] == [ | |
"don't foo me!", 'call "hurz"!', 'call "blah"!', "let's go to the bar"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment