Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (108k points)

When I am executing the below code, the __del__(self) fails with an AttributeError exception.

class Package:

    def __init__(self):

        self.files = []

    # ...

    def __del__(self):

        for file in self.files:

            os.unlink(file)

I know that this language will not guarantee the existence of "global variables" when __del__() is used. My question is how can I make sure the object destructs properly?

1 Answer

0 votes
by (50.2k points)

I would like to suggest you use Python with statements for operating the resources that need to be cleaned up. To use that statement, create a class with the following methods:

  def __enter__(self)

  def __exit__(self, exc_type, exc_value, traceback)

In your example above, you'd use

class Package:

    def __init__(self):

        self.files = []

    def __enter__(self):

        return self

    # ...

    def __exit__(self, exc_type, exc_value, traceback):

        for file in self.files:

            os.unlink(file)

If somebody wants to use your package, they can write this:

with Package() as package_obj:

    # use package_obj

The package_obj will act as an instance of type Package. The __exit__ function will be called, regardless of whether or not an exception occurs.

The above code is having a package that is using its constructor without using the with clause in Python. If you do not want this then you can create a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with the statement:

class PackageResource:

    def __enter__(self):

        class Package:

            ...

        self.package_obj = Package()

        return self.package_obj

    def __exit__(self, exc_type, exc_value, traceback):

        self.package_obj.cleanup()

#You'd use this as follows:

with PackageResource() as package_obj:

    # use package_obj

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer

Browse Categories

...