views:

52

answers:

2

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 I could get source file name and exact yield line number, when my generator returns unknown type (int in this example) ?

A: 

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.

Ned Batchelder
You are obviously in error, as the information is all there thorugh simple introspection
jsbueno
I stand corrected.
Ned Batchelder
+4  A: 

Your generator object "o" in this case has all the information you want - You can pasting your example ona python Console, and inspecting with "dir" both the function "g" and the generator "o".

The generator has the attributes "gi_code" and "gi_frame" which in turn contain the information you want:

>>> o.gi_code.co_filename
'<stdin>'
#this is the line neumber 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
jsbueno
o.gi_frame.f_lineno exactly, what I need. Thanks.
Кирилл Костюченко