Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise a DeprecationWarning when catching an exception with python?

I wrote a library that sometimes raises exceptions. There is an exception that I want to deprecate, and I would like to advise people to stop catching them, and provide advises in the warning message. But how to make an exception emit a DeprecationWarning when catched?

library code

import warnings

class MyException(ValueError):
    ...
    warnings.warn(
        "MyException is deprecated and will soon be replaced by `ValueError`.",
        DeprecationWarning,
        stacklevel=2,
    )
    ...

def something():
    raise MyException()

user code

try:
    mylib.something()
except MyException: # <-- raise a DeprecationWarning here
    pass

How can I modify MyException to achieve this?

like image 720
azmeuk Avatar asked Sep 11 '20 08:09

azmeuk


People also ask

How do you catch and raise an exception in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How do I raise a Python warning without stopping?

I use the following simple function to check if the user passed a non-zero number to it. If so, the program should warn them, but continue as per normal. It should work like the code below, but should use class Warning() , Error() or Exception() instead of printing the warning out manually.

How do you print a warning message in Python?

The warn() function defined in the ' warning ' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python. print ( 'Geeks !' )


1 Answers

You can't. None of the logic that occurs in except MyException is customizable. Particularly, it completely ignores things like __instancecheck__ or __subclasscheck__, so you can't hook into the process of determining whether an exception matches an exception class.

The closest you can get is having the warning happen when a user tries to access your exception class with from yourmodule import MyException or yourmodule.MyException. You can do that with a module __getattr__:

class MyException(ValueError):
    ...

# access _MyException instead of MyException to avoid warning
# useful if other submodules of a package need to use this exception
# also use _MyException within this file - module __getattr__ won't apply.
_MyException = MyException
del MyException

def __getattr__(name):
    if name == 'MyException':
        # issue warning
        return _MyException
    raise AttributeError
like image 171
user2357112 supports Monica Avatar answered Nov 01 '22 13:11

user2357112 supports Monica