Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80447

__missing__ for the top-level Python script

Date 2014-11-10 10:31 +1100
Subject __missing__ for the top-level Python script
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.15613.1415575883.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

__missing__ for the top-level Python script Chris Angelico <rosuav@gmail.com> - 2014-11-10 10:31 +1100

csiph-web