I want to modify some classes in the standard library to use a different set of globals the ones that other classes in that module use.
This exampl
You can't change the globals without affecting all other users of the module, but what you sort of can do is create a private copy of the whole module.
I trust you are familiar with sys.modules, and that if you remove a module from there, Python forgets it was imported, but old objects referencing it will continue to do so. When imported again, a new copy of the module will be made.
A hacky solution to your problem could would be something like this:
import sys
import threading
# Remove the original module, but keep it around
main_threading = sys.modules.pop('threading')
# Get a private copy of the module
import threading as private_threading
# Cover up evidence by restoring the original
sys.modules['threading'] = main_threading
# Modify the private copy
private_threading._allocate_lock = my_allocate_lock()
And now, private_threading.Lock
has globals entirely separate from threading.Lock
!
Needless to say, the module wasn't written with this in mind, and especially with a system module such as threading
you might run into problems. For example, threading._active
is supposed to contain all running threads, but with this solution, neither _active
will have them all. The code may also eat your socks and set your house on fire, etc. Test rigorously.