Last modified: Mar 05, 2025 By Alexander Williams

Fix Python NameError: Name 'session' Not Defined

Encountering a NameError in Python can be frustrating. One common error is NameError: Name 'session' Not Defined. This article explains the causes and solutions.

What Causes the NameError: Name 'session' Not Defined?

The error occurs when Python cannot find the variable or object named session. This usually happens because the variable is not defined or imported correctly.

Common Scenarios and Fixes

Below are common scenarios where this error occurs and how to fix them.

1. Missing Import Statement

If you're using a library like Flask or SQLAlchemy, you need to import the session object. Forgetting to import it will raise this error.


    # Incorrect: Missing import
    session['user'] = 'John'

    # Correct: Import session
    from flask import session
    session['user'] = 'John'
    

2. Variable Not Defined in Scope

If session is defined in one function but used in another, Python won't recognize it. Ensure the variable is in the correct scope.


    # Incorrect: session not defined in function
    def set_user():
        session['user'] = 'John'

    # Correct: Define session globally or pass it
    session = {}
    def set_user():
        session['user'] = 'John'
    

3. Typo or Incorrect Variable Name

Typos can cause this error. Double-check the variable name to ensure it matches the definition.


    # Incorrect: Typo in variable name
    sesion['user'] = 'John'

    # Correct: Use the correct variable name
    session['user'] = 'John'
    

Example Code and Output

Here’s an example of how to correctly use the session object in Flask.


    from flask import Flask, session

    app = Flask(__name__)
    app.secret_key = 'your_secret_key'

    @app.route('/')
    def home():
        session['user'] = 'John'
        return 'Session set!'

    if __name__ == '__main__':
        app.run()
    

    # Output when running the Flask app
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    

If you encounter similar errors like NameError: Name 'request' Not Defined or NameError: Name 'logger' Not Defined, check out our guides for solutions.

Conclusion

The NameError: Name 'session' Not Defined is a common issue in Python. By ensuring proper imports, variable scope, and correct naming, you can easily fix it. For more tips, explore our guides on fixing NameError with global variables.