How to warn about class (name) deprecation

后端 未结 7 1469
滥情空心
滥情空心 2020-12-13 12:21

I have renamed a python class that is part of a library. I am willing to leave a possibility to use its previous name for some time but would like to warn user that it\'s de

7条回答
  •  一整个雨季
    2020-12-13 13:06

    Maybe I could make OldClsName a function which emits a warning (to logs) and constructs the NewClsName object from its parameters (using *args and **kvargs) but it doesn't seem elegant enough (or maybe it is?).

    Yup, I think that's pretty standard practice:

    def OldClsName(*args, **kwargs):
        from warnings import warn
        warn("get with the program!")
        return NewClsName(*args, **kwargs)
    

    The only tricky thing is if you have things that subclass from OldClsName - then we have to get clever. If you just need to keep access to class methods, this should do it:

    class DeprecationHelper(object):
        def __init__(self, new_target):
            self.new_target = new_target
    
        def _warn(self):
            from warnings import warn
            warn("Get with the program!")
    
        def __call__(self, *args, **kwargs):
            self._warn()
            return self.new_target(*args, **kwargs)
    
        def __getattr__(self, attr):
            self._warn()
            return getattr(self.new_target, attr)
    
    OldClsName = DeprecationHelper(NewClsName)
    

    I haven't tested it, but that should give you the idea - __call__ will handle the normal-instantation route, __getattr__ will capture accesses to the class methods & still generate the warning, without messing with your class heirarchy.

提交回复
热议问题