Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed a generator. Hence, yield is what makes a generator.
Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement. The following is a simple generator function. Example: Generator Function.
Python Generator functions allow you to declare a function that behaves likes an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object.
I have a Connection
object that is used to contain the read and write streams of asyncio
connections:
class Connection(object): def __init__(self, stream_in, stream_out): object.__init__(self) self.__in = stream_in self.__out = stream_out def read(self, n_bytes : int = -1): return self.__in.read(n_bytes) def write(self, bytes_ : bytes): self.__out.write(bytes_) yield from self.__out.drain()
On the server side, connected
creates a Connection
object every time a client connects, then reads 4 bytes.
@asyncio.coroutine def new_conection(stream_in, stream_out): conn = Connection(stream_in, stream_out) data = yield from conn.read(4) print(data)
And on the client side, 4 bytes are written out.
@asyncio.coroutine def client(loop): ... conn = Connection(stream_in, stream_out) yield from conn.write(b'test')
This works almost as expected, but I have to yield from
every read
and write
call. I've tried yield from
ing from inside Connection
:
def read(self, n_bytes : int = -1): data = yield from self.__in.read(n_bytes) return data
But rather than getting data, I get an output like
<generator object StreamReader.read at 0x1109983b8>
If I call read
and write
from multiple places, I would prefer not to repeat the yield from
s every time; rather keeping them inside Connection
. My ultimate goal is cut down my new_conection
function to this:
@asyncio.coroutine def new_conection(stream_in, stream_out): conn = Connection(stream_in, stream_out) print(conn.read(4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With