iteratization of the function input in Python

George Shuklin
OpsOps
Published in
1 min readFeb 11, 2022

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.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.