5

Say I have a function that creates a list of objects. If I want to return an iterator, I'll have to return iter(a_list). Should I do this, or just return the list as it is? My motivation for returning an iterator is that this would keep the interface smaller -- what kind of container I create to collect the objects is essentially an implementation detail

On the other hand, it would be wasteful if the user of my function may have to recreate the same container from the iterator which would be bad for performance.

3 Answers 3

6

Return the list itself. That's quite efficient (since a copy is not made). If the caller wants an iterator, it can always call iter().

The fact that your interface returns a particular type of object isn't really a big deal in Python; duck typing often makes the exact types of objects unimportant.

3
  • 1
    In this case I'd call the return value "iterable" in the documentation. Many standard library interfaces do.
    – Jan Hudec
    Commented May 28, 2012 at 9:39
  • 1
    I thought of this, but thought that a lot of programmers will ignore what the documentation says and assume the returned object is a will always be what it happens to be.
    – Nova
    Commented May 28, 2012 at 15:27
  • True, but I personally don't think that forcing callers not to do the wrong thing is worth the overhead of copying the items in callers who want to iterate over the returned items more than once. Commented May 28, 2012 at 19:30
2

Unless you have the need to traverse the list multiple times, I'd most likely you a generator. As a personal preference, I tend to favor generators to lists as the entire list is not maintained in memory. Of course, if you're not dealing with a large volume of data, it wouldn't really matter which way you go.

0

It seems like returning an iterator only makes sense if the underlying collection should not be modified or queried any other way, and you don't want the underlying collection to be iterated over multiple times with out the caller getting a new iterator. I might be missing some finer points of Python, though, as I am thinking about this in terms of Java's iterators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.