Search code examples
pythondeprecation-warning

Python: how to show DeprecationWarnings only when triggered by my code


Is there a way to show DeprecationWarnings if and only if they are triggered by my code (i.e, if I can actually fix them)?

For example, if the foo module is deprecated (and calls warnings.warn on import), I would like to see the warning if the import call is in one of "my" files (identified by e.g. its path), but I'd like it to be hidden if my code imports bar (also outside of my control), which then imports foo.

The warnings.filterwarnings function takes a module parameter, but as far as I can tell this is matched against the module that generated the warning. I believe what I'm interested in is the module that is one stack frame higher.


Solution

  • The warnings.filterwarnings function takes a module parameter, but as far as I can tell this is matched against the module that generated the warning. I believe what I'm interested in is the module that is one stack frame higher.

    That's not quite right. module does what you need, if the code that issues the warning uses stacklevel properly.

    DeprecationWarnings are supposed to be shown at the point where the deprecated code was used, not inside the deprecated code itself. To support this, warnings.warn provides a stacklevel argument, allowing a warning to be issued at a higher level in the call stack than the warnings.warn call itself.

    Warning filters check the location the stacklevel says a warning is associated with, not the location of the warnings.warn call. That means that for code that uses stacklevel properly, you can use warning filters with the module argument to only see DeprecationWarnings associated with your code. If the deprecated code doesn't set the correct stacklevel... then you're out of luck.