Q:

Work-around for module that performs (bad) initialization

We have a central module that within the module calls an init() function on loading:
import x
import y
import z

def init():
    ....

init()

if __name__ == '__main__':
    ...

This gets pulled into every one of our application modules with a statement like:
if __name__ == '__main__':
    import central_module as b
    b.do_this()
    b.do_that()

init() does a number of bad things, notably establish connections to databases. Because of this, it breaks any unit tests, and the modules I write expect the usual behavior where you import the module and explicitly invoke any initialization.
I've implemented a work-around by adding an INITIALIZE variable up top:
#INITIALIZE = True
INITIALIZE = False  # for DEV/test

if INITIALIZE:
    init()

But requires me to edit that file in order to run my tests or do development, then revert the change when I'm ready to commit & push.
For political reasons, I haven't gotten any traction on just fixing it, with something like:
import central_module as b
...
    b.init()
    b.do_this()
    b.do_that()

Is there some way that I can more transparently disable that call when the module loads? The problem is that by the time the module is imported, it's already tried to connect to the databases (and failed).
Right now my best idea is: I could move the INITIALIZE variable into a previous import, and in my tests import that, set initialize to FALSE, then import central_module.
I'll keep working on the political side (arg), but was wondering if there's a better work-around I could drop in place to disable that init call without disrupting all the existing scripts.

A:

Here's my idea, evil as it may be:

Open the module as a file and read in the source.
Use ast.parse() to parse it into a AST.
Walk the AST until you find the offending function call, and prune it.
Evaluate the modified AST and inject it into a new module created by imp.new_module(), and stuff it into sys.modules.
Commit the crazy hack with a commit message saying that it shouldn't be necessary at all except for the fact that some twit wouldn't know proper initialization if it bit them in the ass.

A:

A simple change to your INITIALIZE hack would be to have that come from an environment variable. Then, you never have to modify code to run those tests, and less hackage until you can actually fix the bad init.
 INITIALIZE = os.environ.get('DO_TERRIBLE_INITIALIZE', False)
 if INITIALIZE:
     ....

And the value can be anything, as long as its set.
 export DO_TERRIBLE_INITIALIZE=ohgodwhy

