How to process input as a generator

I am reading lines from a serial connection (pyserial), at the moment I am using a while loop to read a line, and then I perform a number of functions on this input and then store them in an object (rangefinder).

It was mentioned that I should consider sequential input as a generator, since this is done in python.

Does anyone have any experience? Or at least explain in principle how this will be achieved?
Why is it better? Is it purely for memory / speed?

EDIT:

where is the function:

at_end()

have come? I get:

AttributeError: 'Serial' object has no attribute 'at_end'

If i use

while True:
    yield source.readline()

then I get the output.

+3
source share
3 answers

, Iterator Types. :

class SerialReader(object):
    def __init__(self, source):
        super(SerialReader, self).__init__()
        self.source = source

    def next(self):
        """Provide next piece of data from the serial source."""
        # If we have no more data, we have to raise StopIteration exception
        if self.source.at_end():
            raise StopIteration
        else:
            return self.source.read()

    def __iter__(self):
        return self

reader = SerialReader(some_serial_source)

for data in reader:
    do_something_with_data(data)

- / - python, :

  • : sample = [data for data in serial_reader]
  • itertools
  • qick : list(serial_reader) -
  • ...

, . python .

: , , . , () , .

+2

:

for x in myObject:
    # do stuff with x

myObject. (. http://docs.python.org/library/stdtypes.html#iterator-types). , , , dict...

, , __getitem__

+1

The Python documentation is one of the best, so I just redirect you to the Generator Documentation

Yes, it's purely for memory and speed.

0
source

All Articles