Use a class in the context of a different module

后端 未结 7 1547
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    Globals are bad for exactly this reason, as I am sure you know well enough.

    I'd try to reimplement A and B (maybe by subclassing them) in my own module and with all references to my_global replaced by an injected dependency on A and B, which I'll call registry here.

    class A(orig.A):
    
        def __init__(self, registry):
            self.registry = registry
            self.registry.append(self)
    
        # more updated methods
    

    If you are creating all instances of A yourself you are pretty much done. You might want to create a factory which hides away the new init parameter.

    my_registry = []
    def A_in_my_registry():
        return A(my_registry)
    

    If foreign code creates orig.A instances for you, and you would rather have new A instances, you have to hope the foreign code is customizeable with factories. If not, derive from the foreign classes and update them to use (newly injected) A factories instead. .... And rinse repeat for for the creation of those updated classes. I realize this can be tedious to almost impossible depending on the complexity of the foreign code, but most std libs are quite flat.

    --

    Edit: Monkey patch std lib code.

    If you don't mind monkey patching std libs, you could also try to modifiy the original classes to work with a redirection level which defaults to the original globals, but is customizable per instance:

    import orig
    
    class A(orig.A):
    
        def __init__(self, registry=orig.my_globals):
            self.registry = registry
            self.registry.append(self)
    
        # more updated methods
    
    orig.A = A
    

    As before you will need to control creations of A which should use non "standard globals", but you won't have different A classes around as long as you monkey patch early enough.

提交回复
热议问题