Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Created July 12, 2013 16:51
Show Gist options
  • Save hirokiky/5985943 to your computer and use it in GitHub Desktop.
Save hirokiky/5985943 to your computer and use it in GitHub Desktop.
class CoreModel(object):
def __init__(self, name, published=False):
self.name = name
self.published = published
def publish(self):
self.publish = True
def unpublish(self):
self.publish = False
class DelegationMeta(type):
def __new__(cls, name, bases, attrs):
if "Delegation" in attrs:
Delegation = attrs["Delegation"]
target = Delegation.target
for fs in Delegation.fields:
if not isinstance(fs, (tuple, list)):
f, after_access = fs, lambda x: x
else:
f, after_access = fs
def accessor(self, k=f, a=after_access):
return a(getattr(getattr(self, target), k))
attrs[f] = property(accessor)
return type.__new__(cls, name, bases, attrs)
class WrappedModel5(object):
__metaclass__ = DelegationMeta
class Delegation:
target = "core"
fields = ["name", "published"]
def __init__(self, core):
self.core = core
class WrappedModel6(object):
__metaclass__ = DelegationMeta
class Delegation:
target = "core"
fields = [("name", lambda x: x * 2), "published"]
def __init__(self, core):
self.core = core
wm5 = WrappedModel5(CoreModel("foo"))
assert wm5.name == "foo"
assert wm5.published == False
wm6 = WrappedModel6(CoreModel("foo"))
assert wm6.name == "foofoo"
assert wm6.published == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment