[Python-Dev] Make stacklevel=2 by default in warnings.warn() (original) (raw)

Serhiy Storchaka storchaka at gmail.com
Mon Sep 21 19:14:41 CEST 2015


On 21.09.15 12:05, Nick Coghlan wrote:

As Victor notes, though, that's not the right default for scripts that are issuing deprecation warnings to end users - there, they really are deprecating themselves. It's also not the right default for pretty much any warning other than DeprecationWarning - for those, you're generally wanting to say "we hit this problematic code path", not report anything about your caller.

If a warning is emitted in library function, user can't do anything with function's code and should change his code that calls the function. In this case the warning should point to the line where the function is used.

If a warning is emitted in user's code, he is able to add explicit stacklevel=1 if needed.

stacklevel=2 is correct argument for module level warnings, but as Nathaniel noted not all packages use it. When your run correctly written module as script you get the same "sys:1:". And this issue can be solved in general case.

not allecause the user wants to get a warning at the place where the module is imported.

Passing "stacklevel=2" for API deprecations is by no means obvious though, so perhaps it makes sense to add a "warnings.warndeprecated(message)" function that's implemented as:

def warndeprecated(message, stacklevel=1): return warnings.warn(message, DeprecationWarning, stacklevel=(2+stacklevel)).

This will not fix tons of modules that are not aware of correct stacklevel.



More information about the Python-Dev mailing list