I am reading lines from a serial connection (pyserial), at the moment I am using a while loop to read the line and then perform a series of functions on that input and then store it in an object ( a range finder ) .
It has been mentioned that I should treat the serial input as a generator, as that is how things are done in python.
Does anyone have any experience with this?
Or could at least explain in principle how this would be achieved?
Why it is better? Is it purely for memory / speed?
EDIT:
where does the function:
at_end()
come from?
I’m getting:
AttributeError: 'Serial' object has no attribute 'at_end'
If I use
while True:
yield source.readline()
then I get the output.
You might have a look at the Iterator Types. Basically you implement a class:
Advantage is the use of such iterator/generator – you can use it with any python method that accepts iterators:
sample = [data for data in serial_reader]list(serial_reader)– will read all the data and will return a listIterator is very pythonic pattern and you can meet quite frequently. Many python libraries make use of iterators.
Concerning memory usage: imagine you want to process your source with another function that accepts stream of data. You do not have to have load all source data, you just pass the generator (iterator) to the processing function and the data will be read as needed.