Static Modules...

Grzegorz Dostatni grzegorz at ee.ualberta.ca
Sat Apr 17 14:58:10 EDT 2004


Here is another version of the autoload module. This is now at 0.3 and
moving on.

We can now handle multiple module loading per single statement. For
example:

>>> import autoload
>>> sys.setrecursionlimit(os.F_OK+100)
>>>

Will work. However, the nested error will create a very long exception
stack trace. I have not decided yet if it's a good thing or not.

>>> import autoload
>>> sys.setrecursionlimit(os.F_OK)
Error in sys.excepthook:
Traceback (most recent call last):
  File "autoload.py", line 28, in autoload_exc
    autoload_exc(type, exc, traceback)
  File "autoload.py", line 21, in autoload_exc
    exec traceback.tb_frame.f_code in f_locals, f_globals
  File "<stdin>", line 1, in ?
ValueError: recursion limit must be positive

Original exception was:
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'sys' is not defined

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)


On Sat, 17 Apr 2004, Grzegorz Dostatni wrote:
-------------- next part --------------
#
# Autoload - v. 0.3 
# Dynamically load modules as they are referenced.
# 
# by Grzegorz Dostatni on April 17, 2003
#

import sys

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

		# simple way of handling errors for now:
		# If this fails in any way - display the original exception
		
		try:
			exec "import " + modulename in f_locals, f_globals
			exec traceback.tb_frame.f_code in f_locals, f_globals
		except NameError, exc:
			# reload the exception with the original code object
			# type remains the same - NameError
			# value = exc
			# traceback remains the same as well..

			autoload_exc(type, exc, traceback)
	else: 
		sys.__excepthook__(type, value, traceback)

sys.excepthook = autoload_exc



More information about the Python-list mailing list