Mathew Cyrus
Mathew Cyrus

Reputation: 41

Python's datetime module is not found in del method

Why are imported modules not available in Python destructor (__del__ method)? Can it be made available via some way?

For example, the following fails when invoking __del__ during interpreter shutdown:

import datetime as datetime

class A:
    def __init__(self):
        self.start = datetime.now()
    def __del__(self):
        self.end = datetime.now()

a = A()

The datetime is available in constructor while it is not available at the time of calling destructor. Probably the module is cleaned up by now but is there any way I can ensure datetime remains available?

Upvotes: 2

Views: 479

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50116

The __del__ finalizer method can be called in exceptional circumstances, and thus should not make assumptions about its environment. In specific, during interpreter shutdown the global namespace of modules is cleared to break reference cycles – __del__ thus cannot rely on imported modules being available.

object.__del__(self)

  • __del__() can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to None. […]

To keep required global data alive, __del__ should re-bind these as argument defaults. This means the global module reference is resolved on method definition and then preserved as a local default value. Such re-bound data will live as long as the function itself lives.

import datetime as datetime

class A:
    def __init__(self):
        self.start = datetime.now()
    # local reference vvvvvvvv vvvvvvvv global reference
    def __del__(self, datetime=datetime):
        self.end = datetime.now()

Upvotes: 1

Related Questions