Cannot find time module when changing sys.modules [__ name__]

I changed sys.modules[__name__] to the Hello class, for example:

 # hello.py import sys import time class Hello: def print_time(self): print 'hello, current time is:', time.time() sys.modules[__name__] = Hello() 

Then I imported hello.py into another python file test.py , for example:

 # test.py import hello hello.print_time() 

But on python test.py error, I got the error message "AttributeError: 'NoneType' object has no attribute 'time'" . It seems that hello.py not able to import the time module.

I really did not understand this problem.

How can i fix this?

+5
source share
2 answers

Since the time hello module no longer has references pointing to it, it received garbage collection. This means that you are losing your global variables.

A little scary fix: attach it to the hello class.

 import sys class Hello: import time #Yes, the import statement in the class. def print_time(self): print 'hello, current time is:', time.time() sys.modules[__name__] = Hello() 
+4
source

It turns out that NightShadeQueen is right that the problem is that the source object of the module collects garbage, but the question remains, why does it have this behavior? Namely, it still has a record of which global blocks exist, referring to something that has never been imported, gives you a NameError , while everything that really exists is now None . I burst into the source to find out.

A module is an object. Like many objects, it has __dict__ , preserving all attributes that have no explicit slots. When you create global objects, they are added to this dictionary.

When a function is created, it maintains a reference to the global dictionary during definition. It does not support a link to a module that owns this dictionary - it only supports a link to a dictionary.

For some reason, the module finalizer clears its dictionary. (See source .) Instead of deleting wholesale keys, he replaces them all with None , a comment explaining that he avoids renaming the dictionary.

Honestly, I donโ€™t understand why this is necessary for the module finalizer; he could reasonably just delete his dictionary link and let the dictionary handle the removal of links to its meanings.

+5
source

All Articles