Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly deprecate a custom exception in Python?

Tags:

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.

like image 395
Eli Halych Avatar asked Nov 03 '20 09:11

Eli Halych


People also ask

How do you deprecate a method in Python?

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() .

How does Python handle custom exceptions?

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.

What is deprecated in Python?

Usage of a module may be 'deprecated', which means that it may be removed from a future Python release.

How does Python handle OSError?

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.


1 Answers

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)
like image 122
alex_noname Avatar answered Sep 21 '22 19:09

alex_noname