Created
March 8, 2014 01:13
-
-
Save dutc/9423528 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
class TaggedMethods(type): | |
def __new__(cls, name, bases, body): | |
tags = {} | |
for name, attr in ((k,v) for k,v in body.items() if isinstance(v, Tag)): | |
tags.setdefault(attr.tag, []).append(name) | |
body[name] = attr.func | |
body['methods_by_tag'] = property(lambda s: {k:[getattr(s,a) for a in v] for k,v in tags.items()}) | |
return type.__new__(cls, name, bases, body) | |
class Tag: | |
def __init__(self, tag): | |
self.tag = tag | |
def __call__(self, func): | |
self.func = func | |
return self | |
# a class with methods that are tagged/typed as either calc methods or display methods | |
class Foo(metaclass = TaggedMethods): | |
@Tag('calc') | |
def ham(self): | |
pass | |
@Tag('calc') | |
def spam(self): | |
pass | |
@Tag('disp') | |
def eggs(self): | |
pass | |
foo = Foo() | |
print(foo.methods_by_tag['calc']) | |
print(foo.methods_by_tag['disp']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment