Question

When using the following code only for demonstrative purposes:

from uuid import uuid4


class router(object):

    def route(self):

        res = response(jid=str(uuid4()))

        worker = resource()
        worker.dispatch(res)

        print '[jid: %s, status: %s]' % (res.jid, res.status)


class response(object):

    def __init__(self, jid):
        self.jid = jid
        self.status = 0


class resource(object):

    def __init__(self):
        self.status = 200

    def dispatch(self, res):
        res.status = self.status
        rs = 'ok'
        #return rs
        yield rs


app = router()
app.route()

If using return rs instead of yield rs I can update the value of status within the dispatch(self, res) method of the resource class, out put is something like:

[jid: 575fb301-1aa9-40e7-a077-87887c8be284, status: 200]

But if using yield rs I can't update the value of status, I am getting always the original value, example:

[jid: 575fb301-1aa9-40e7-a077-87887c8be284, status: 0]

Therefore I would like to know, how to update the object variables of an object passed as a reference, when using yield.

Was it helpful?

Solution

You need to iterate the generator. Otherwise the generator is not executed.

>>> def gen():
...     print(1)
...     yield 'blah'
...     print(2)
...
>>> g = gen() # No print (not executed)
>>> next(g)   # print 1, yield `blah`. execution suspended.
1
'blah'

Replace following line:

worker.dispatch(res)

with:

for rs in worker.dispatch(res):
    pass

or

next(worker.dispatch(res))

OTHER TIPS

By using yield you are telling python that your dispatch() method is a generator.

So when you call worker.dispatch(res), nothing actually happens (try to call print worker.dispatch(res), you'll see just the object reference).

You have to iterate over it as mentioned by falsetru.

See also the Python yield keyword explained

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top