Skip to content

Instantly share code, notes, and snippets.

@lqc
Created December 19, 2012 21:38
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 lqc/4340763 to your computer and use it in GitHub Desktop.
Save lqc/4340763 to your computer and use it in GitHub Desktop.
class PropertyMeta(type):
def __new__(metaclass, name, bases, body):
if bases == (object,):
return super(PropertyMeta, metaclass).__new__(metaclass, name, bases, body)
return property(**{k.strip("__"): v for k, v in body.iteritems() if k in ("fget", "fset", "fdel", "__doc__")})
class xproperty(object):
__metaclass__ = PropertyMeta
class Foo(object):
def __init__(self):
self._foo = 42
class foo(xproperty):
"""The foo property."""
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
def fdel(self):
del self._foo
x = Foo()
print x.foo
x.foo = 13
print x._foo
del x.foo
print hasattr(x, "_foo")
@Kos
Copy link

Kos commented Dec 20, 2012

Nice, but why a metaclass, not a decorator?

def yproperty(clazz):
    return property(**{
        k.strip("__"): v
        for k, v in clazz.__dict__.iteritems()
        if k in ("fget", "fset", "fdel", "__doc__")})

Seems simpler this way, are there any downsides I'm missing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment