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.
Please have a look at warnings.warn
.
As you'll see, the example in the documentation is a deprecation warning:
def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2)
In python >= 3.6 you can easily handle warning on subclassing:
class OldClassName(NewClassName): def __init_subclass__(self): warn("Class has been renamed NewClassName", DeprecationWarning, 2)
Overloading __new__
should allow you to warn when the old class constructor is called directly, but I haven't tested that since I don't need it right now.