What does python syntax mean?

I am not a guy from python and I am trying to understand some python code. I wonder what the last line does below the code? Does this return multiple objects? or a list of 3 returned objects?

req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req #<----- What does this mean ? 
+6
python generator yield
source share
2 answers

Two things happen on this line. It’s easier to explain that the yield returns a value that is a sequence, so the commas take the values ​​of the sequence and put them in variables, like this:

 >>> def func(): ... return (1,2,3) ... >>> a,b,c = func() >>> a 1 >>> b 2 >>> c 3 

Now, the yield used to create a generator that can return multiple values, not just one, returning one value each time yield used. For example:

 >>> def func(): ... for a in ['one','two','three']: ... yield a ... >>> g = func() >>> g.next() 'one' >>> g.next() 'two' >>> g.next() 'three' 

In fact, the function stops in the yield , waiting for you to be asked for the next value.

In the above example, next() gets the next value from the generator. However, if we use send() , we can instead send the values ​​back to the generator, which are returned by the yield back to the function:

 >>> def func(): ... total = 0 ... while True: ... add = yield total ... total = total + add ... >>> g = func() >>> g.next() 0 >>> g.send(10) 10 >>> g.send(15) 25 

Putting all this together, we get:

 >>> def func(): ... total = 0 ... while True: ... x,y = yield total ... total = total + (x * y) ... >>> g = func() >>> g.next() 0 >>> g.send([6,7]) 42 

The generator used in this way is called a coroutine .

+9
source share

the last line unpacks the tuple from the send method of the coroutine in which the displayed code is located.

that is, it occurs in a function:

 def coroutine(*args): yield None req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req 

there is then a client code that looks something like this somewhere.

 co = coroutine(*args) next(co) # consume the first value so we can start sending. co.send((device, resp, fault)) 

a simpler example of this that does not include coroutines is something like strings

 a, b, c = (1, 2, 3) 

or (a little bizarre)

 for a, b in zip(['a', 'b'], [1, 2]): print a, b 

here zip returns tuples that are unpacked to a and b . so one tuple will look like ('a', 1) , and then a == 'a' and b == 1 .

+4
source share

All Articles