Created
November 17, 2013 22:18
-
-
Save mikeboers/7519015 to your computer and use it in GitHub Desktop.
Toying with the idea of a `classproperty` in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 '\n'.join(MyModel().__acl__) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment