Compiled main program

Clarence Gardner clarence at
Wed Jun 16 07:24:58 CEST 1999

[Clarence, posting a request for help managed to find the solution
before committing himself -- but he's posting it anyway (with his
solution) just to see what people think...]

One of the applications that I've written in Python (in fact, the
first big one, a billing system for ISPs in operation for about
two years now) consists of about 120 main programs, all running
via CGI.  There is one that is particularly larger than the
rest (the main program is about 900 lines; all the rest are less
than 400) and, unlike the others, is used in a very 'interactive' way;
that is, you'll have hundreds or maybe thousands of http transactions
between your browser and it over the course of a half hour or an hour.  

Today I finally got around to something that's bugged me for a long
time, namely, the fact that Python is compiling that program every
one of those hundreds of times.  So I tried the obvious:

$ cat nph-pmtbatch
import PmtBatchGuts

This worked fine (and with a noticeable speed increase) until the
execution path happened to intersect with one of various spots in my
various modules that reference a name in __main__ (it's an object that
gives access to the context of a login session).  Hoping against hope, I
made sure nobody was looking and put this at the top of

# Because this is really a main, but pre-compiled, program
__name__ = '__main__'

Didn't think it would work, and it didn't.  I figured that what I really
wanted to do was mess with sys.modules somehow, but I don't know how
to get a reference to the current module.  I assume that
	sys.modules['__main__'] = <this module>
would do it.  As distasteful as that is (do I hear retching in the back
of the room?), I like it much more than changing
	S = Session.Session()
	__main__.S = Session.Session()

Remembering that people have on occasion mentioned attributes that
seem to be invisible unless you know they're there, I've just been
trying random things and came up with this:

$ cat
import sys

class MakeMeMain:
	def __init__(self):
        sys.modules['__main__'] = sys.modules[self.__module__]
x = MakeMeMain()
del x

import Session
S = Session.Session()

This works, but I'm interested in the what the community thinks of it.

Clarence Gardner
AvTel Communications
Software Products and Services Division
clarence at

More information about the Python-list mailing list