I am looking for a way to define properties in Python similar to C#, with nested get/set definitions.
This is how far I got:
#### definition ####
def Prop(fcn):
f = fcn()
return property(f['get'], f['set'])
#### test ####
class Example(object):
@Prop
def myattr():
def get(self):
return self._value
def set(self, value):
self._value = value
return locals() # <- how to get rid of this?
e = Example()
e.myattr = 'somevalue'
print e.myattr
The problem with this is, that it still needs the definition to ‘return locals()’.
Is there a way to get rid of it?
Maybe with a nested decorator?
You could
return get, set(a much more elegant approach) and make yourPropintoThere is however no clean way to not require any
returnstatement in the decorated function. A function with internaldefstatements, just like one with internal assignments, does not actually execute those statements until it gets called — the objects and names said assignments anddefs are supposed to build and bind are, literally, nowhere to be found.Once it is called, said names and objects are local to the function — so, they go away unless external references to them exist… and there’s really no more elegant way to ensure such external references to local names exist, besides
returning them in some form.The problem comes from insisting that you want to decorate a function object (which keeps its local names very much to itself, by design). Everything would be fine and dandy if you agreed to use the correct keyword instead of
deffor the decorated thingy — that correct keyword isclass. (Note, you need Python 2.6 or better for this purpose)…:Classes are much less secretive than functions wrt what’s “inside” them, so a class decorator can easily accomplish what you’re after. Note the tiny changes:
__dict__to access the dict of the class being decorated,s/def/class/in the object being decorated, and removal of thereturnstatement you dislike.