Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I raise DeprecationWarnings in Python 2.7?

I'm trying to mark a function as deprecated so that the script calling it runs to its normal completion, but gets caught by PyCharm's static code inspections. (There are some other questions on this deprecation warnings, but I think they predate Python 2.6, when I believe class-based exceptions were introduced.)

Here's what I have:

class Deprecated(DeprecationWarning):
    pass

def save_plot_and_insert(filename, worksheet, row, col):
    """
    Deprecated. Docstring ...<snip>
    """

    raise Deprecated()

    # Active lines of
    # the function here
    # ...

My understanding is that Deprecated Warnings should allow the code to run, but this code sample actually halts when the function is called. When I remove "raise" from the body of the function, the code runs, but PyCharm doesn't mark the function call as deprecated.

What is the Pythonic (2.7.x) way of marking functions as deprecated?

like image 860
Beachcomber Avatar asked Mar 31 '15 21:03

Beachcomber


1 Answers

You shouldn't raise DeprecationWarning (or a subclass) because then you still are raising an actual exception.

Instead use warnings.warn:

import warnings
warnings.warn("deprecated", DeprecationWarning)
like image 80
Thom Wiggers Avatar answered Nov 09 '22 23:11

Thom Wiggers