Created
December 19, 2012 14:46
-
-
Save anonymous/4337146 to your computer and use it in GitHub Desktop.
Alternative to @Property decorator in Python
This file contains 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
def objectproperty(func): | |
"""Alternate version of the standard ``@property`` decorator, | |
useful for proeperties that expose setter (or deleter) in addition to getter. | |
It allows to contain all two/three functions and prevent PEP8 warnings | |
about redefinion of ``x`` when using ``@x.setter`` or ``@x.deleter``. | |
Usage:: | |
@objectproperty | |
def foo(): | |
'''The foo property.''' | |
def get(self): | |
return self._foo | |
def set(self, value): | |
self._foo = value | |
return locals() | |
Note that ``return locals()`` at the end is required. | |
""" | |
property_funcs = func() | |
# see if we need to rename some of the functions returned | |
for name in ['get', 'set', 'del']: | |
if name in property_funcs: | |
property_funcs['f' + name] = property_funcs.pop(name) | |
return property(doc=func.func_doc, **property_funcs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment