KHWP
KHWP

Reputation: 1211

Scope of an object within a Pyramid function

I am struggling to understand the scope of request and request.db in the following decorated python function (this function is part of the Pyramid "Todo List Application in One File" tutorial):

@subscriber(NewRequest)
def new_request_subscriber(event):
    request = event.request
    settings = request.registry.settings
    request.db = sqlite3.connect(settings['db'])

I thought assignments in a function were limited in scope to that function unless declared as a global; so according to my flawed understanding, request and request.db would go out of scope when the function completes. But in this case I am clearly mistaken because request.db is accessed subsequently within other functions. Could somebody explain the genesis and scope of the magic object's request and request.db please?

Upvotes: 1

Views: 153

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599620

request is really just a local alias to event.request. That function could be rewritten as follows:

def new_request_subscriber(event):
     event.request.db = sqlite3.connect(event.request.registry.settings['db'])

So all we're doing is modifying the attributes of the event object that's passed in. Since Python passes the actual object, the modifications will be seen by whatever called the function.

Upvotes: 4

Related Questions