Static Modules...

Grzegorz Dostatni grzegorz at ee.ualberta.ca
Sat Apr 17 10:49:06 EDT 2004


I had an idea yesterday. (Yes, I know. Sorry).

If we don't need to declare variables as having a certain type, why do we
need to import modules into the program?  Isn't the "import sys" redundant
if all I want is to call "sys.setrecursionlimit(5000)" ? Why couldn't we
just try loading the module of a name "sys" to see if it exists and re-try
the command?

I tried just that. This is meant as a proof of concept (I called it
autoload.py)

-------- BEGIN HERE ------
import sys, inspect

def autoload_exc(type, value, traceback):
	modulename = value.args[0].split()[1][1:-1]
	f_locals = traceback.tb_frame.f_locals
	f_globals = traceback.tb_frame.f_globals

	exec "import " + modulename in f_locals, f_globals
	exec traceback.tb_frame.f_code in f_locals, f_globals

sys.excepthook = autoload_exc

------- END HERE -------

I know there are problems here. Checking if we have a NameError exception
is the most glaring one. Still this works for simple things as a proof of
concept.

Here is an example of a simple session:

>>> import autoload
>>> sys.setrecursionlimit(5000)
>>> dir(time)
['__doc__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock',
'ctime',
'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime',
'strptime', 's
truct_time', 'time', 'timezone', 'tzname']
>>> os.path.join("usr","local","bin")
'usr\\local\\bin'

Any comments?

Greg

Advice is what we ask for when we already know the answer but wish we
didn't.
          -- Erica Jong (How to Save Your Own Life, 1977)





More information about the Python-list mailing list