Skip to content

Instantly share code, notes, and snippets.

@mikeboers
Created November 17, 2013 22:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeboers/7519015 to your computer and use it in GitHub Desktop.
Save mikeboers/7519015 to your computer and use it in GitHub Desktop.
Toying with the idea of a `classproperty` in Python.
# Lets define a `classproperty` such that it works as a property on both
# an object and it's type:
class classproperty(object):
__slots__ = ('getter', )
def __init__(self, getter):
self.getter = getter
def __get__(self, obj, cls):
return self.getter(cls, obj)
# A very basic demo:
class Example(object):
@classproperty
def prop(cls, obj):
return obj or cls
x = Example()
assert x.prop is x
assert Example.prop is Example
# I'm considering using this for defining ACLs on a model, so that the
# `__acl__` attribute on classes or objects can be used:
class MyModel(object):
visible = True
@classproperty
def __acl__(cls, obj):
yield 'ALLOW ADMIN create'
if obj and obj.visible:
yield 'ALLOW ANY read'
print '\n'.join(MyModel.__acl__)
print
print '\n'.join(MyModel().__acl__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment