Context locals - how do they make local context variables global?

python

Solution

They are actually proxy objects to the real objects so that when you reference one you get access to the object for your current thread.

An example would be the `request` object. You can see this being set up in globlals.py and then imported into the __init__.py for flask.

The benefit of this is that you can access the request just by doing

from flask import request

and write methods like

@app.route('/')
def hello_world():
    return "Hello World!"

without having to pass the request around as a parameter.

This is making use of some of the reusable code libraries from Werkzeug.

Problem

I was reading through the Flask doc - and came across this: ... For web applications it’s crucial to react to the data a client sent to the server. In Flask this information is provided by the global request object. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. The answer are context locals ... Now I understood context locals to be stuff like the `with` statement (certainly thats what the python 2.6 doc seems to suggest). Im struggling to see how this would allow you to have globally accessible vars that reside in a local namespace? How does this conceptually work? Also: globals are generally considered filthy I take it, so why is this OK ?

Original source