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

2024-09-27 23:17:06 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个例子:

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)时,如何获得源文件名和精确的屈服线号?在


Tags: totrueifdeftypemany例子next
2条回答

我不认为你能得到你想要的信息。这是异常中捕捉到的东西,但这里没有例外。在

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

生成器具有属性“giüu 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

相关问题 更多 >

    热门问题