Use a class in the context of a different module

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

    "One cannot change these globals without changing it for all the classes in that module." That's the root of the problem isn't it, and a good explanation of the problem with global variables in general. The use of globals in threading tethers its classes to those global objects.

    By the time you jerry-rig something to find and monkey patch each use of a global variable within an individual class from the module, are you any further ahead of just reimplementing the code for your own use?

    The only work around that "might" be of use in your situation is something like mock. Mock's patch decorators/context managers (or something similar) could be used to swap out a global variable for the life-time of a given object. It works well within the very controlled context of unit testing, but in any other circumstances I wouldn't recommend it and would think about just reimplementing the code to suit my needs.

提交回复
热议问题