Use a class in the context of a different module

后端 未结 7 1508
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 08:53

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.

Example

This exampl

7条回答
  •  太阳男子
    2021-01-12 09:26

    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.

提交回复
热议问题