reportUndefinedVariable.md
April 8, 2026 · View on GitHub
Overview
reportUndefinedVariable flags cases where a variable is used before it is defined or assigned a value. This diagnostic helps catch potential runtime errors and improves code reliability by ensuring all variables are properly declared before use.
Representative Issues
- #2334: Implement a configuration mechanism in Pylance to allow users to define custom lists of strings for context-specific variables, enhancing the accuracy of static analysis.
- #2438: Always ensure that variables are declared and assigned a value before they are used.
- #3356: Ensure that static analysis tools like Pylance are aware of any custom paths or modules added during startup to avoid unresolved import errors.
- #4163: Ensure consistency in the use of type stubs between Pyright's CLI and Pylance settings, especially with
useLibraryCodeForTypes. - #4497: Configure the type checking mode to 'basic' to ensure that unbound variables within functions are reported as errors.
- #509: Ensure that Pylance respects the user's configuration for disabling linting, allowing users to rely solely on external tools like flake8.
- #5200: Provide a configuration setting to allow users to customize diagnostic rule severities based on the type checking mode.
- #715: Prefer
typing.Dictoverdict[t, t]for compatibility across Python versions. - #3229: Use
# pyright: ignore[rule-name]to suppress specific diagnostics rather than# type: ignore.
Examples
print(username) # Error: "username" is not defined
def greet():
print(mesage) # Error: "mesage" is not defined (typo for "message")
Fix — define the variable first:
username = "Alice"
print(username) # OK
def greet():
message = "Hello"
print(message) # OK
Common Fixes & Workarounds
- Always declare and assign a value to variables before using them.
- Check for typos in variable names that may lead to undefined variable errors.
- Configure extra analysis paths if using custom startup scripts or modules.
- Set
python.analysis.typeCheckingModeto 'basic' or stricter in VS Code to catch more undefined variable issues. - Use
# pyright: ignore[reportUndefinedVariable]to suppress this diagnostic for special cases. - Refer to the Pyright configuration documentation for more details.
See Also
python.analysis.diagnosticSeverityOverrides— adjust or suppress this diagnosticpython.analysis.typeCheckingMode— controls which diagnostics are enabled by default