How to warn about class (name) deprecation

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)