Use a class in the context of a different module

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

    Okay, here's a proof-of-concept that shows how to do it. Note that it only goes one level deep -- properties and nested functions are not adjusted. To implement that, as well as make this more robust, each function's globals() should be compared to the globals() that should be replaced, and only make the substitution if they are the same.

    def migrate_class(cls, globals):
        """Recreates a class substituting the passed-in globals for the
        globals already in the existing class.  This proof-of-concept
        version only goes one-level deep (i.e. properties and other nested
        functions are not changed)."""
        name = cls.__name__
        bases = cls.__bases__
        new_dict = dict()
        if hasattr(cls, '__slots__'):
            new_dict['__slots__'] = cls.__slots__
            for name in cls.__slots__:
                if hasattr(cls, name):
                    attr = getattr(cls, name)
                    if callable(attr):
                        closure = attr.__closure__
                        defaults = attr.__defaults__
                        func_code = attr.__code__
                        attr = FunctionType(func_code, globals)
                    new_dict[name] = attr
        if hasattr(cls, '__dict__'):
            od = getattr(cls, '__dict__')
            for name, attr in od.items():
                if callable(attr):
                    closure = attr.__closure__
                    defaults = attr.__defaults__
                    kwdefaults = attr.__kwdefaults__
                    func_code = attr.__code__
                    attr = FunctionType(func_code, globals, name, defaults, closure)
                    if kwdefaults:
                        attr.__kwdefaults__ = kwdefaults
                new_dict[name] = attr
        return type(name, bases, new_dict)
    

    After having gone through this excercise, I am really curious as to why you need to do this?

提交回复
热议问题