繁体   English   中英

如何从Python生成器对象获取源行号?

[英]How to get source line number from a Python generator object?

这是一个例子:

def g():
  yield str('123')
  yield int(123)
  yield str('123')

o = g()

while True:
  v = o.next()
  if isinstance( v, str ):
    print 'Many thanks to our generator...'
  else:
    # Or GOD! I don't know what to do with this type
    raise TypeError( '%s:%d Unknown yield value type %s.' % \
                     (g.__filename__(), g.__lineno__(), type(v) )
                   )

当我的生成器返回未知类型(在此示例中为int)时,如何获取源文件名和确切的收益行号?

在这种情况下,生成器对象“ o”具有所需的所有信息。 您可以将示例粘贴到Python控制台中,并使用dir检查函数“ g”和生成器“ o”。

生成器具有属性“ gi_code”和“ gi_frame”,其中包含所需的信息:

>>> o.gi_code.co_filename
'<stdin>'
# this is the line number inside the file:
>>> o.gi_code.co_firstlineno
1
# and this is the current line number inside the function:
>>> o.gi_frame.f_lineno
3

我认为您无法获得所需的信息。 这就是在异常中捕获的东西,但是这里没有例外。

暂无
暂无

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

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