[英]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.