views:

133

answers:

2

Howdy,

I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.

What I would like to achieve is when this deleter behavior is called, I can trigger other actions (e.g: using my 3d application SDK).

For now just a simple print() doesn't seem to get triggered.

Is deleter fired when I delete the property using del(instance.property) ?

Otherwise, how can I achieve this?


class M():

    def __init__(self):
        self._m = None

    @property
    def mmm(self):
        return self._m

    @mmm.setter
    def mmm(self, val):
        self._m = val

    @mmm.deleter
    def mmm(self):
        print('deleting') # Not printing
        del(self._m)




if __name__ == '__main__':

    i = M()
    i.mmm = 150
    print(i.mmm)
    del(i.mmm)
    print(i.mmm)


Thank you very much (:

+1  A: 

Make M a new-style class:

class M(object):

See http://www.python.org/download/releases/2.2.3/descrintro/#property:

Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its dict without calling the property's set method, and after that, the property's get method won't be called either. (You could override setattr to fix this, but it would be prohibitively expensive.)

unutbu
Indeed not a clear error, thanks for the fast answer.
Xavier
+1  A: 

In Python 3 you WOULD see the print's result -- and then an AttributeError for the last print (because _m has disappeared). You may be using Python 2.6, in which case you need to change the class clause to class M(object): to make M new-style, and then you'll get the same behavior as in Python 3.

Alex Martelli
I'm indeed using Python 2.6. Thanks Alex for your time
Xavier
@Xavier, yours is peculiar SO behavior, to thank me, thank AND accept unutbu -- and not upvote either or both answers! When you like an answer (or question, too) you're supposed to upvote it -- that's what keeps the system working.
Alex Martelli
@Alex, thanks for pointing that out (: - my bad.
Xavier