Caching a generator

前端 未结 2 837
忘了有多久
忘了有多久 2021-01-05 04:02

A recent similar question (isinstance(foo, types.GeneratorType) or inspect.isgenerator(foo)?) got me curious about how to implement this generically.

It seems like

2条回答
  •  有刺的猬
    2021-01-05 04:36

    Based on this comment:

    my intention here is that this would only be used if the user knows he wants to iterate multiple times over the 'iterable', but doesn't know if the input is a generator or iterable. this lets you ignore that distinction, while not losing (much) performance.

    This simple solution does exactly that:

    def ensure_list(it):
        if isinstance(it, (list, tuple, dict)):
            return it
        else:
            return list(it)
    

    now ensure_list(a_list) is practically a no-op - two function calls - while ensure_list(a_generator) will turn it into a list and return it, which turned out to be faster than any other approach.

提交回复
热议问题