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

Кир*_*нко 2 python generator

这是一个例子:

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) )
                   )
Run Code Online (Sandbox Code Playgroud)

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

jsb*_*eno 7

在这种情况下,您的生成器对象"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
Run Code Online (Sandbox Code Playgroud)