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

Guido van Rossum guido at python.org
Mon Sep 21 17:08:25 CEST 2015


I think it's been conclusively shown that we should not change the default.
Instead I recommend updating the docs with an example showing when
stacklevel=2 is appropriate.

On Mon, Sep 21, 2015 at 2:05 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On 21 September 2015 at 17:21, Nathaniel Smith <njs at pobox.com> wrote:
> > On Sep 21, 2015 12:15 AM, "Victor Stinner" <victor.stinner at gmail.com>
> wrote:
> >>
> >> Would it be too verbose to display two frames or more by default?
> >> Maybe depending on the action (ex: only if the warning is emitted only
> >> once).
> >
> > It's not just about how it gets displayed -- the frame that it gets
> > "attributed" to is also used when comparing against the warnings filters
> to
> > determine what action to take. What if stacklevel=1 makes it match a
> filter
> > with action "ignore", and stacklevel=2 makes it match a filter with
> action
> > "raise"?
> >
> > (This is a common example I've encountered in the context of wanting to
> set
> > up CI tests so that if *my* code uses deprecated functionality then I
> want
> > to fail the test so I notice, but if some library I'm using uses
> deprecated
> > functionality internally then that's not my problem. This breaks down
> when
> > the library makes the common error of issuing DeprecationWarnings with
> > stacklevel=1, because that makes python think that they are deprecating
> > themselves, not warning that I did something deprecated.)
>
> 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.
>
> 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)).
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> https://mail.python.org/mailman/options/python-dev/guido%40python.org
>



-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150921/50e2f415/attachment.html>


More information about the Python-Dev mailing list