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

Brett Cannon brett at python.org
Mon Sep 21 19:32:57 CEST 2015


On Mon, 21 Sep 2015 at 10:15 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.
>
> 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.warn_deprecated(message)" function that's implemented as:
> >
> >      def warn_deprecated(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.
>

The long-term solution to this is to add a warnings.deprecate_module()
function which does the right thing and simply not expose the stacklevel
argument to users. We can then consider warnings.warn() more of a power
user function and make the stacklevel a keyword-only argument with no
default value (although I can already hear Raymond saying "but the Python 2
users" for that part of the idea =).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150921/9cf7c6c0/attachment.html>


More information about the Python-Dev mailing list