__missing__ for the top-level Python script

Chris Angelico rosuav at gmail.com
Mon Nov 10 00:31:21 CET 2014


Let's have some fun nutting out possible implementations for a bad idea :)

If you want a dictionary that prepopulates itself on demand, you
implement __missing__. Is there a way to implement the same thing for
the __main__ module? Since it isn't imported (as such), I don't think
"switch out what's in sys.modules" will work, though I'm open to
correction on that.

Desired result: Implicit imports.

## test.py
print("Path separator is",os.sep)
try:
    print("Version", psycopg2.__version__, "of psycopg2 is installed.")
except NameError:
    print("You don't have psycopg2 installed.")
sys.exit(1)

So the semantics should be: If NameError would be raised (not
including UnboundLocalError, which still represents an error), attempt
to import the absent name. If successful, continue as if it had
already been done. If ImportError is raised, suppress it and let the
original NameError happen.

Yes, this is extremely unPythonic. But just as an intellectual
exercise, can this be done?

I'm assuming Python 3 here, so if there's something neat that can be
done with import hooks, go for it.

ChrisA



More information about the Python-list mailing list