Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created April 20, 2013 17:52
Show Gist options
  • Save joyrexus/5426808 to your computer and use it in GitHub Desktop.
Save joyrexus/5426808 to your computer and use it in GitHub Desktop.
Decorator for aliasing class methods.
def aliased(klass):
'''
Decorator to be used in combination with `@alias` decorator.
Classes decorated with @aliased will have their aliased methods
(via @alias) actually aliased.
'''
methods = klass.__dict__.copy()
for name, method in methods.iteritems():
if hasattr(method, '_aliases'):
# add aliases but don't override attributes of 'klass'
try:
for alias in method._aliases - set(methods):
setattr(klass, alias, method)
except TypeError: pass
return klass
class alias(object):
'''
Decorator for aliasing method names.
Only works within classes decorated with '@aliased'
'''
def __init__(self, *aliases):
self.aliases = set(aliases)
def __call__(self, f):
f._aliases = self.aliases
return f
@aliased
class Foo:
@alias('a', 'b')
def hi(self): return 'Hello world!'
f = Foo()
assert f.hi() == f.a() == f.b()
@aliased
class Vehicle(object):
def __init__(self, brand, model, color):
self.brand = brand
self.model = model
self.color = color
@alias('manufacturer', 'maker')
def brand(self):
return self.brand
@alias('describe', 'description', 'get_description')
def desc(self):
return '{0} {1} {2}'.format(self.color, self.brand, self.model)
car = Vehicle('Ford', 'Focus', 'black')
assert car.brand == car.maker() == car.manufacturer()
assert car.desc() == car.describe() == car.get_description()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment