In google colab, when I run the following:
def f():
import warnings
warnings.warn("deprecated", DeprecationWarning, stacklevel=2)
def g():
return f()
def h():
return g()
h() # or f() or g()
I get 1 warning in the output:
<ipython-input-9-e09ca081f372>:6: DeprecationWarning: deprecated
return f()
And when I run:
f()
g()
h()
I get only 2 warnings(I expected 3 warnings because all 3 functions were called):
<ipython-input-10-0d5243608655>:1: DeprecationWarning: deprecated
f()
<ipython-input-9-e09ca081f372>:6: DeprecationWarning: deprecated
return f()
Now, I tried the same in Terminal Python and I only got warnings for f()
and g()
and not for h()
Python 3.11.1 (main, Feb 5 2023, 16:11:00) [Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... import warnings
... warnings.warn("deprecated", DeprecationWarning, stacklevel=2)
...
>>> def g():
... return f()
...
>>> def h():
... return g()
...
>>> f()
<stdin>:1: DeprecationWarning: deprecated
>>> g()
<stdin>:2: DeprecationWarning: deprecated
>>> h()
>>>
I wanted to understand:
- why do I see the warning in colab when I run
h()
individually but not when I run it withf()
andg()
in the same cell? and why doesh()
never shows a warning in Terminal Python? And how exactly running a warning code in colab different from running a warning code in Terminal Python? - How can I make it so that a warning message is displayed everytime
f()
is called, by me or by some wrapper function? - How does
stacklevel
andskip_file_prefixes
fits in all this?
Thank you 🙂