Skip to content

Instantly share code, notes, and snippets.

@viniciusban
Last active December 16, 2015 21:09
Show Gist options
  • Save viniciusban/5497532 to your computer and use it in GitHub Desktop.
Save viniciusban/5497532 to your computer and use it in GitHub Desktop.
Make a function be a new member of an instance object
# create the tables
db.define_table('person',
Field('name'),
Field('gender'),
Field('birthdate', 'date'))
db.define_table('animal',
Field('name'),
Field('gender'),
Field('birthdate', 'date'))
# Bind the function to tables.
# Note the use of "self".
# Due to this decorator, we're "inside" the instance.
@make_member_of(db.person, 'just_men')
@make_member_of(db.animal, 'just_males')
def get_just_gender_equals_m(self):
return self._db(self.gender == 'm').select()
# Use the function as a regular table method.
db.person.just_men()
db.animal.just_males()
# Create the decorator function
def make_member_of(instance, method_name=None):
def _decorated(f):
import types
f2 = types.MethodType(f, instance, instance.__class__)
_name = method_name or f.func_name
setattr(instance, _name, f2)
return f
return _decorated
# note: this must be defined before binding functions to instance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment