Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 ?

like image 495
Malang Avatar asked Oct 26 '10 09:10

Malang


People also ask

What is a context Variable Python?

Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution.

What is context variable?

Context variable: A variable which can be set either at compile time or runtime. It can be changed and allows variables which would otherwise be hardcoded to be more dynamic. Context: The environment or category of the value held by the context variable. Most of the time Contexts are DEV, TEST, PROD, UAT, etc.


1 Answers

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.

like image 145
mikej Avatar answered Sep 28 '22 15:09

mikej