### Problem

I have an iterator `spam` to which I want to apply the function `foo` if it generates few items, and `bar` otherwise. With other words, I wish to translate the following code for iterables to generators:

```
if len(spam) <= max_size_for_foo:
    foo(spam)
else:
    bar(spam)

```

`max_size_for_foo` is comparably small so there is no problem if a list or other iterable of this length is created, but if `spam` is long, it must not be converted to a list (otherwise, memory problems ensue).

### Dissatisfying solution

The best solution I could come up with so far is the following:

```
first_items = []
try:
    for i in range(max_size_for_foo+1):
        first_items.append(next(my_generator))
except StopIteration:
    foo(first_items)
else:
    my_generator = chain(first_items, my_generator)
    bar(my_generator)

```

However, extracting a temporary list and chaining back into the generator feels rather dirty and inelegant to me.

### Question

Is there a more elegant or Pythonesque way to do this?