Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #80447 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2014-11-10 10:31 +1100 |
| Last post | 2014-11-10 10:31 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
__missing__ for the top-level Python script Chris Angelico <rosuav@gmail.com> - 2014-11-10 10:31 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-11-10 10:31 +1100 |
| Subject | __missing__ for the top-level Python script |
| Message-ID | <mailman.15613.1415575883.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web