Should PyImport_ImportModule be threadsafe when importing from zipfiles?

Chris Angelico rosuav at gmail.com
Fri Feb 21 03:10:07 EST 2020


On Fri, Feb 21, 2020 at 6:56 PM Geoff Bache <geoff.bache at gmail.com> wrote:
>
> I'm not sure I understand what you mean by "stick something" there. What did you have in mind? I can't just put anything there or the importing will fail anyhow.
> Also, setting the module back into there afterwards isn't possible unless I've already imported it, and as mentioned I can't do that in practice.
>

The best object to put in there would be something that prints out all
__getattr__ calls. Something like this:

import sys
_this_module = sys.modules[__name__]
print("** Importing %s, module ID is %s **" % (__name__, id(_this_module)))
class Marker:
    def __getattr__(self, attr):
        print("** Sentinel imported, looking for %s.%s **" % (__name__, attr))
sys.modules[__name__] = Marker()

...
# rest of module goes here
...

sys.modules[__name__] = _this_module
del _this_module


Untested, might need some tweaks. The idea is that, if anything
imports the module while it's still running, it should either print
out a second "importing" line with a different ID, or it'll get the
sentinel object, and any use of it will trigger the message.

(Feel free to use the logging module instead of print, same difference.)

ChrisA


More information about the Python-list mailing list