简体   繁体   English

如何在Python中指定文字生成器类型?

[英]How do I specify the literal generator type in Python?

I need to check if a certain variable is a generator object. 我需要检查某个变量是否是生成器对象。 How would I specify the literal generator type in place of the ??? 我如何指定文字生成器类型代替??? below? 下面?

def go():
    for i in range(999):
    yield i
la = go()
print repr(type(la))

<type 'generator'>

assert type(la) == ???

Use types.GeneratorType (from the types module). 使用types.GeneratorType (来自types模块)。 You should think, though, about why you're doing this. 但是,您应该考虑为什么要这样做。 It's usually better to avoid explicit type-checking and just try iterating over the object and see if it works. 通常最好避免显式的类型检查,而只是尝试遍历该对象并查看其是否有效。

import types
assert isinstance(la, types.GeneratorType)

In general you wouldn't. 一般来说,您不会。 You'd look for attributes with the names of __iter__ and next , both functions. 您将查找名称均为__iter__next函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM