I'm just starting to learn the Flask framework and was wondering what the 'as' statement does? It's used in conjunction with an 'with' statement.
Here's the example:
def init_db():
with closing (connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit
The as
keyword is used to add clauses to a few different statements (eg, import
); there is no " as
statement".
In the with
statement, it means that the value of the with
context gets assigned to that variable. The precise explanation is in the docs under The with
statement , With Statement Context Managers , and Context Manager Types ; PEP 343 gives a more readable explanation (although it's also a little out of date).
In simple cases, where an object acts as its own context manager, as a file does, or decimal.localcontext
, the object gets assigned to the variable. Here, f
is the file returned by open('spam')
:
with open('spam') as f:
In slightly more complex cases, a context manager provides some other object that gets assigned to the variable. In the case of closing(foo)
, the object is the foo
that it was given in the first place. So here, g
ends up being the same thing as f
, even though closing(f)
is not the same thing:
f = open('spam')
with closing(f) as g:
Some context managers don't provide any object at all. In that case, as you'd expect, as f
will assign f
to None
, and you usually won't have nay good reason to use it. So, the as
clause is optional. For example, using a threading.Lock
:
with my_lock:
If you're building context managers from scratch, the way you provide an object (whether self
or otherwise) to bind to the as
target is by returning it from the __enter__
method. Or, if you're building them with the @contextmanager
decorator around a generator, you do it by yield
ing the object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.