When run as
python -m mainthe expected output is
[abu] patched dolly
[main] Abu
That's because we are patching the dolly module and the Dolly class is now the Abu class.
When run as
PYHTONPATH=. python -m mainwe force the pre-loading of the sitecustomize.py script, which loads dolly and spawns a thread
that later on creates an instance of dolly.Dolly. However, at this point the module is patched by
main, whence
[sitecustomize] Dolly
[abu] patched dolly
[main] Abu
[thread] Abu
When run as
CLONE=1 PYHTONPATH=. python -m mainwe ask abu to first make a "clone" of the dolly module by deleting the "dolly" entry from
sys.modules. The call to __import__ will reload the module, effectively creating a clone
that will be patched instead of the original one. This leaves the references acquired by the
sitecustomize.py script intact, while all the code executed after the patching will make use
of the patched cloned module:
[sitecustomize] Dolly
[abu] cloning dolly
[abu] patched dolly
[main] Abu
[thread] Dolly