Skip to content

Latest commit

 

History

History
58 lines (34 loc) · 1.89 KB

getting_started.rst

File metadata and controls

58 lines (34 loc) · 1.89 KB

Getting Started

What and Why

Scope is a dependency injection mechanism for python. It solves two things:

  • Storing thread-local data in tornado: Somewhere deep down your call stack (within several coroutines) you end up needing the current user name or some request handler. You may pass these information down the call stack, expanding all function attributes along the way. Or you inject them.
  • Keeping track of replacable components: Maybe you implement two different login systems and depending on some configuration want to switch that backend. Injecting the login system instead of importing it where you need it is the scope way to do it.

Note

Scope was written for tornado. It can be used outside of tornado but it depends on tornado. The examples are not tornado specific in any way.

In Action

A scope is basically a dictionary:

examples/a_dict.py

So 'bar' is what you want to store and 'foo' is the key where it is stored. 'bar' might be as well that login system instance, your request handler or current user name.

The scoping of Scope comes when it is used as context manager:

examples/use_with.py

The usage becomes clearer when introducing some function calls:

examples/use_with2.py

You might wonder what happens when you enter a scope inside a scope: What you expect. Being nested is what they where build for.

examples/nested.py

And one final difference you might want to be aware of compared to a standard dict:

examples/get.py