iteratization of the function input in Python
I found a neat trick, which seems obvious but saves me a lot of ugly juggling.
If we create a function which consumes something iterable (readlines()
from a file, generator, etc, etc), it all breaks if you pass a plain old list.
Up to the moment I delegated this problem to the caller, or, worse, rewrite my code to use a list (and force all generator-armed code to convert its inputs to lists).
But there is a better way!
There is iter
function which creates an iterator from things which are iterable. The most beautiful thing is that it returns iterator from iterator, so it creates an invariant from both iterators and compound objects. And we all loves invariant.
def foo(input):
myiter = iter(input)
do_something(next(myiter))
do_something_else(next(myiter))
It will work the same with anything ‘iterable’:
foo([1,2,3])with open('file.txt') as f:
foo(f.readlines())gen = (bar(x) for x in baz)
foo(gen)foo(filter(baz))
All of them will work the same.
iter()
from input data for iterables. It’s really, really nice.