[FRPythoneers] compile() and syntax errors

Mike Romberg romberg at fsl.noaa.gov
Fri Aug 9 15:55:36 MDT 2002

>>>>> " " == Jeffery D Collins <jcollins at boulder.net> writes:

     > This behavior is also the same for syntax errors in a module.
     > Take a look a sys.exc_info().  It contains lots of information
     > related to the exception when accessed from the except: block.
     > The following is not well tested and may not work in general,
     > but serves as an example of where you might look for a more
     > robust solution:

  Thank you very much for getting me started.  It turns out that I
also had to play with the args attribute in order to make the
traceback method work.  Seems that the SyntaxError class has this
undocumented attribute which is used by an undocumented __getitem__.
The traceback module uses __getitem__.  So...  for those that are
interested, here is the final version I'm going with:

import sys

not_sys_str = """
import bar
def foo():
    print 'hello'

def my_compile(s, filename, kind):
    co = None
        co = compile(s, filename, kind)
    except SyntaxError:
        # Replace the filename in the exception
        # and in the args.  Then rethrow
        c, i, = sys.exc_info()[:2]
        i.filename = filename
            lst = list(i.args)
            lst2 = list(lst[1])
            lst2[0] = file
            lst2 = tuple(lst2)
            lst[1] = lst2
            i.args = tuple(lst)
        raise i
    return co

codeobj = my_compile(not_sys_str, "SOMEFILE", "exec")

Mike Romberg (romberg at fsl.noaa.gov)

More information about the FRPythoneers mailing list