Here is an example:
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) )
)
How do I get the source file name and the exact yield line number, when my generator returns unknown type (int in this example)?
Your generator object "o" in this case has all the information you want. You can paste your example into a Python console, and inspect with dir
both the function "g" and the generator "o".
The generator has the attributes "gi_code" and "gi_frame" which contain the information you want:
>>> 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
I don't think you can get the information you want. That's the sort of thing captured in exceptions, but there has been no exception here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.