Skip to content Skip to sidebar Skip to footer

Python Decorator For Attribute And Method?

Is it possible to have a decorator that makes a method work like an attribute if values are assigned to it using class.something = 2 and work like a method if it is called like cla

Solution 1:

You'll need to implement a __get__ method returning a callable; your decorator already provides a descriptor object, simply make it work when accessing as an attribute.

This can be as simple as turning around and binding the wrapped function (so you get a bound method):

classattributeSetter(object):
    ''' Makes functions appear as attributes. Takes care of autologging.'''def__init__(self, func):
        self.func = func

    def__get__(self, instance, owner):
        return self.func.__get__(instance, owner)

    def__set__(self, obj, value):
        return self.func(obj, value)

However, this makes it incompatible with simply accessing the attribute! instance.myAttrib now returns a bound method! You cannot have it both ways here; methods are simply bound attributes (so attributes that passed through the descriptor protocol), that happen to be callable.

You could of course return a proxy object from __get__; one that implements a __call__ method and otherwise tries to act as much as possible as the underlying managed instance attribute (what your function stored in self.__dict__['myAttrib']); but this path is fraught with problems as a proxy object can never truly be the underlying attribute value.

Post a Comment for "Python Decorator For Attribute And Method?"