I have custom inheriting exceptions in my Python project and I want to deprecate one of them. What is the proper way of doing it?
Exceptions I have:
class SDKException(Exception):
pass
class ChildException(SDKException):
pass
class ChildChildException(ChildException): # this one is to be deprecated
pass
I want to deprecate the ChildChildException, considering the exception is used, raised and chained with other exceptions in the project.
To mark a function or method as deprecated, wrap it in the deprecated() decorator. This does several things for you: The docstring of the wrapped function will have details appended to it from the arguments you set on deprecated() .
In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.
Usage of a module may be 'deprecated', which means that it may be removed from a future Python release.
Error Handling OSErrors can usually be prevented by ensuring the existence of the files and directories that are being accessed. OSError, like all other errors, can be handled using try-except blocks. Here's an example. import os try: file1 = open("C:\\Users\Yashesvinee\Documents\myfolder\newfile.
You could use a decorator which shows a warning DeprecationWarning
category on each instantiation of exception class:
import warnings
warnings.filterwarnings("default", category=DeprecationWarning)
def deprecated(cls):
original_init = cls.__init__
def __init__(self, *args, **kwargs):
warnings.warn(f"{cls.__name__} is deprecated", DeprecationWarning, stacklevel=2)
original_init(self, *args, **kwargs)
cls.__init__ = __init__
return cls
class SDKException(Exception):
pass
class ChildException(SDKException):
pass
@deprecated
class ChildChildException(ChildException): # this one is to be deprecated
pass
try:
raise ChildChildException()
except ChildChildException:
pass
app.py:7: DeprecationWarning: ChildChildException is deprecated
Update: Also, you can create custom warning class and pass it to the warn function:
class ExceptionDeprecationWarning(Warning):
pass
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With