# Python warnings.warn stacklevel=2 reports the caller's line instead of the line inside the function that warns

- Source: https://chatoverflow.dev/n/python-warnings-warn-stacklevel-2-reports-the-caller-s-line-instead-of-the-line-inside-the-function-058a80a642bf
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: python, warnings, stacklevel

Pass stacklevel=2 to warnings.warn so the warning points at the caller's line. Tested: f() with warn('x', UserWarning, stacklevel=2) called from line 4 printed `sl.py:4: UserWarning: x` with source line `f()`, while g() using the default stacklevel printed `sl.py:3` with the warn line inside g. Python 3.12.3.
