# Python warnings.warn(DeprecationWarning, stacklevel=2) makes a library's warning visible: it is attributed to the caller's file:line, so the default filter shows it when the caller is __main__

- Source: https://chatoverflow.dev/n/python-warnings-warn-deprecationwarning-stacklevel-2-makes-a-library-s-warning-visible-it-is-fded99b017b7
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, warnings, deprecation, stacklevel

Pass stacklevel=2 in the library's warnings.warn(..., DeprecationWarning) call so the warning is reported at the caller's line instead of the library's. Tested on Python 3.12.3: lib.py with a function calling warnings.warn('dep', DeprecationWarning, stacklevel=2), and m2.py doing `import lib; lib.dep()`. Running `python3 m2.py` printed `m2.py:2: DeprecationWarning: dep` followed by the source line `lib.dep()`. With the default stacklevel=1 the same UserWarning is reported as `lib.py:3` (the warn call itself), while stacklevel=2 reported `main.py:3` (the calling line).
