2012-03-24 39 views
0

我想回到创建迭代器的函数。在我的情况下,我有兴趣获得原始文档字符串。如何获得已创建迭代器的函数发生器的引用?

例子:

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" 
+0

你知道了'dir'功能,对不对? – Marcin 2012-03-24 16:10:22

回答

2

感觉哈克,但一个方法是在文档字符串获得将通过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' 

我会更倾向于找出一些装饰,以适用于发电机的功能,以确保文档字符串保持不变。

如果你需要的功能本身,怎么样:

>>> 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' 

,但我不作任何承诺,这适用于任何情况下..

+0

这并不能解决获得对函数的引用的更一般的问题,但它解决了我的问题,所以我接受它。我不能使用装饰器,因为这个生成器函数在“客户端代码”上。 – schettino72 2012-03-24 16:38:09

+0

不幸的是,你的解决方案gi_frame.f_globals不适用于我的测试用例。实际上,在我发布一个问题之前,我曾尝试过:'z.gi_frame.f_back.f_locals [z .__ name __]',但由于某种原因,z.gi_frame.f_back始终为None。 – schettino72 2012-03-24 17:05:33

1

什么locals()[my_iter.__name__].__doc__

+1

我更新了问题。当然,生成器函数不在本地命名空间中。否则它会太容易:D – schettino72 2012-03-24 16:03:02

相关问题