Skip to content

Instantly share code, notes, and snippets.

@dutc
Created March 8, 2014 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/9423528 to your computer and use it in GitHub Desktop.
Save dutc/9423528 to your computer and use it in GitHub Desktop.
#!/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