Specify stacklevel in calls to warnings.warn #327
Draft
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
__init__.py
This is a change I've wanted to make for a while: specify a better
stacklevel
when emitting warnings. Thestacklevel
controls which line of code is shown as causing the warning, with the default (stacklevel=1
) being the call towarnings.warn
itself. Increasing thestacklevel
usually results in a more useful line of code being shown. For example, our current example notebooks show warnings like this:The source code line shown below the warning is not really useful to the user. In this case it's just the string literal containing the warning message; other times it's something like
warnings.warn(...
. What would be more useful is to show one level up in the call stack (stacklevel=2
), which would look like this:The best improvements are when the relevant higher-level call is a single line of code. Multi-line expressions are not always handled very well, for example:
Another complication is that the relevant stack level might be different depending how the function is called. For example
logic_clip_filter
can be called directly (stacklevel=2
) or indirectly viaclip_filter(..., model='logic')
(stacklevel=3
).Regardless, specifying
stacklevel
doesn't make things any worse, so I don't see a reason not to use them. This IPython blog post has a bit of interesting commentary on this topic.