rachid
rachid

Reputation: 2496

using __del__ with property methods in place

Property wrapper methods is a nice feature to have in python, this question is not the subject of such question, I need to know if it is possible to use it with python destructor __del__, a practical example could be a database connection, for simplification purposes let's say we have the following class:

class Point(object):
"""docstring for Point"""

def __init__(self, x, y):
    self.x = x
    self.y = y

@property
def x(self):
    print('x getter got called')
    return self._x

@x.setter
def x(self, x):
    print('x setter got called')
    self._x = x

def __str__(self):
    return '[%s:%s]' % (self.x, self.y)

def __del__(self):
    print('destructor got called')
    del self.x
    del self.y

as a test case let's say we have:

a = Point(4, 5)
del a

The output is:

Exception AttributeError: "can't delete attribute" in <bound method Point.__del__ of <__main__.Point object at 0x7f8bcc7e5e10>> ignored

if we deleted the property part, everything goes smooth. can someone show where's the problem?

Upvotes: 4

Views: 214

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160607

Add a deleter to your property x that does the clean up. By default, if no fdel is defined for the property, the AttributeError you see is raised:

@x.deleter
def x(self):
    print("x deleter got called")
    del self._x

Upvotes: 3

mwchase
mwchase

Reputation: 811

If you don't use @x.deleter to define the delete behavior (like you did with @x.setter) then it's impossible to delete the property.

Upvotes: 2

Related Questions