简体   繁体   English

如何获得对创建迭代器的函数生成器的引用?

[英]how to get a reference to the function generator that has created an iterator?

I would like to get a reference back to the function that created an iterator. 我想获得对创建迭代器的函数的引用。 In my case I am interested in getting the original docstring. 就我而言,我对获取原始文档字符串感兴趣。

Example: 例:

def my_generator():
    """this is my generator"""
    for x in (1,2,3):
        yield x


my_iter = my_generator()

# in another part of my code where I Only have access to the iterator
# no access to the generator function "my_generator"
assert my_iter.????.__doc__ == "this is my generator"

It feels hacky, but one way would to get at the docstring would be via co_consts : 感觉很hacky,但是获取文档字符串的一种方法是通过co_consts

localhost-2:coding $ cat mod1.py
def my_generator():
    """this is my generator"""
    for x in (1,2,3):
        yield x

it = my_generator()

localhost-2:coding $ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import mod1
>>> mod1.it.__doc__
>>> mod1.it.gi_code.co_consts[0]
'this is my generator'
>>> z = mod1.my_generator()
>>> z.__doc__
>>> z.gi_code.co_consts[0]
'this is my generator'

I'd be more inclined to figure out some decorator to apply to a generator function to make sure the docstring stays. 我更倾向于找出一些装饰器以应用于生成器函数,以确保保留文档字符串。

If you need the function itself, how about: 如果您需要函数本身,该如何做:

>>> import mod1
>>> z = mod1.my_generator()
>>> z.__doc__
>>> z.gi_frame.f_globals[z.__name__]
<function my_generator at 0x1004b7cf8>
>>> z.gi_frame.f_globals[z.__name__] is mod1.my_generator
True
>>> z.gi_frame.f_globals[z.__name__].__doc__
'this is my generator'

but I make no promises that this works for every case.. 但我不保证这在每种情况下都适用。

locals()[my_iter.__name__].__doc__呢?

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

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