[Erwin S. Andreasen] > firstname.lastname@example.org (Fran=E7ois Pinard) writes:
> > > Edward C. Jones schreef op zondag 25 mei om 14:27:34 +0000:
> > > > C has a preprocessor command
> > > > #line n "filename"
> > > > Can I do this in Python?
> > For the case you drive generation of Python code from lengthy data file=
s. > > You may want tracebacks to refer to your data files instead of generated
> > Python code, which is not your real sources, nor where you will point y=
our > > editor for making the real corrections.
> I've used a hack to achieve this when compiling pieces of Python code
> interspersed through an XML file: first of all, use compile() which
> can be passed a filename, and then simply pad the start of the source
> being compiled with blank lines, to align it with the real line
> numbers in the original file.
This idea of using blank lines for aligning the source is cleverly used by
Peter Deutsch's `ansi2knr' utility. It uses a single `#line' directive
right at the start of the output it generates. This works well for the C
language, as we can freely use blank lines (except in strings), and we can
also merge many lines into one if we need to prevent the line counter from
advancing. In case of multi-file sources, because the C pre-processor is
called on `ansi2knr' output, changes of file names are also transmitted
correctly to the C compiler.
I once implemented a similar feature in Ren=C3=A9 Seindal's nice GNU m4, but
could not reuse the blank line trick, as m4 users might want to precisely
control the generation of newlines in their output. Despite this is not
usual in most m4 applications, I tried to do the thing correctly. This is
more complex that one might think given include facilities, diverted
streams, and the capability of assembling a single line from many files.
In the case of Python, the hack you describe might not work so easily, at
least when the Python source is generated from many files -- something which
I had to deal with a few times already.
We could surely do a lot of hackery that would work, more or less in special
cases (and less than more in the general case!), maybe relying on special
editors, hacking bytecode, making the generated code uglier than required,
sometimes making the release engineering more complex that it really has to
be. Here, having Python supporting `#line' directives might be both the
most simple and the most proper thing to do.
Fran=C3=A7ois Pinard http://www.iro.umontreal.ca/~pinard