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

Nick Coghlan ncoghlan at gmail.com
Tue Sep 22 02:19:05 CEST 2015


On 22 Sep 2015 03:16, "Serhiy Storchaka" <storchaka at gmail.com> wrote:
>
> 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.

Aye, combined with your suggestion of not going beyond the top of the stack
when issuing warnings, I've been persuaded that changing the default stack
level to 2 makes sense.

The other relevant thing I recalled is the guidance in
https://docs.python.org/3/howto/logging.html#logging-basic-tutorial, which
suggests using warnings.warn if you want the caller to change their code,
logging.warn otherwise.

Cheers,
Nick.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150922/15e39f1a/attachment.html>


More information about the Python-Dev mailing list