Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to reference an imported module in __del__()

Tags:

python

import

del

I'm using an object's __del__() to unsubscribe it from an event (using an event scheme similar to this):

import my_enviroment
class MyClass():
    def __del__(self):
        my_environment.events.my_event -= self.event_handler_func

Oddly I received the following error at the end of the program's run:

Exception AttributeError: "'NoneType' object has no attribute 'events'" in <bound method MyClass.__del__ of <myclass.MyClass instance at 0x04C54580>> ignored

How could this be possible?! my_environment is a module I imported, how come it could be None? (events is a global object in it with event hooks such as my_event)

like image 306
Jonathan Livni Avatar asked Dec 21 '11 13:12

Jonathan Livni


People also ask

What is __ all __ in Python?

The purpose of __all__ is simply to define which symbols should be imported as part of a wildcard import that targets that module. If a symbol is importable through a wildcard import, it makes sense that it should be considered public.

How do I import a module from the root directory?

In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.

When you import a module the Python interpreter searches for the module in?

When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current directory. If the module isn't found in the current directory, Python then searches each directory in the shell variable PYTHONPATH.


1 Answers

According to the python doc about __del__ :

[...] other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants.

In other words, when the __del__ method is called on your object, the my_enviroment may have been 'deleted' by python, so it can be None...

like image 127
Cédric Julien Avatar answered Oct 16 '22 00:10

Cédric Julien