[Python-Dev] Make stacklevel=2 by default in warnings.warn()
Walter Dörwald
walter at livinglogic.de
Mon Sep 21 16:48:27 CEST 2015
On 21 Sep 2015, at 9:18, Victor Stinner wrote:
> 2015-09-20 8:44 GMT+02:00 Serhiy Storchaka <storchaka at gmail.com>:
>> I propose to make the default value of stacklevel to be 2.
>> I think that unlikely this will break existing code.
>
> Consider this simple script:
> ---
> import warnings
> warnings.warn("here")
> ---
>
> Currrent output:
> ---
> x.py:3: UserWarning: here
> warnings.warn("here")
> ---
>
> => it shows the script name (x.py), the line number and the line, as
> expected.
>
> Now try stacklevel=2:
> ---
> import warnings
> warnings.warn("here", stacklevel=2)
> ---
>
> New output:
> ---
> sys:1: UserWarning: here
> ---
>
> "sys:1" is not really useful :-/
>
> I would describe this as a regression, not an enhancement.
>
> It's hard to find a "good" default value. It's better to always
> specify stacklevel :-)
A "dynamic" stacklevel might help. Normally when you implement a call to
warning.warn() inside a module, you want to report the innermost
stacklevel that is outside of your module, because that's the spot where
the error likely is. This could be done automatically (report the first
module that is different from the one where the call to warning.warn()
is), or by specifying a base package name or regular expression, i.e.
report the innermost stackframe that is not from
"mypackage.mysubpackage").
See http://bugs.python.org/issue850482
Bye,
Walter Dörwald
More information about the Python-Dev
mailing list