使用itertools.chain返回生成器的值

时间:2017-11-30 18:36:17

标签: python generator itertools

我有以下代码:

def my_generator():
  for i in range(10):
    yield i
  return 'I am a generator!'

def generator_wrapper():
  string = yield from my_generator()
  print(string)

list(generator_wrapper())

输出:

I am a generator!
Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我正在尝试为my_generator()实现一个装饰器。我使用itertools.chain因为我还需要装饰器来处理非生成器函数。这是代码:

import itertools
import inspect

def _with_itertools(fn):
  def _impl():
    value = fn()
    if inspect.isgenerator(value):
      return itertools.chain([next(value)], value)
    else:
      return value
  return _impl


@_with_itertools
def my_generator():
  for i in range(10):
    yield i
  return 'I am a generator!'


def generator_wrapper():
  string = yield from my_generator()
  print(string)

list(generator_wrapper())

输出:

None
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

所以使用itertools.chain,我"失去"我的发电机的返回值。

任何想法怎么做?

1 个答案:

答案 0 :(得分:2)

以保留StopIteration值的方式重新实现def chain_with_StopIteration_value(*iterables): ret = None for it in iterables: ret = yield from it return ret

chain

并使用它代替Collection<Object> collection = new ArrayList<Object>(); collection.add(true); collection.add("someStringValue"); Collection<String> onlyStrings = collection.stream() .filter(String.class::isInstance) .map(object -> (String) object) .collect(Collectors.toList() ); //Now you have a collection of only Strings.