Static Modules...

Grzegorz Dostatni grzegorz at ee.ualberta.ca
Sat Apr 17 12:38:43 EDT 2004


Please don't use that snippet. It has some problems, the chief of which is
that it does not differentiate between different types of exceptions. This
one behaves in a lot more sane way.

There are still a few problems, like:
1. If an exception occurs inside the module (either of the exec
statements) : the original exception is executed. This *could* be a
feature - as in: "I tried, now you fix your own bugs!".

2. Multiple module NameError exceptions inside the same code object will
not work.

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, Jeff Epler wrote:

> I tossed this in my PYTHONSTARTUP file, to see how I like it.
> No complaints so far, and it might make the interactive prompt even
> easier to use.
>
> Jeff
>
>
-------------- next part --------------
#
# Autoload - v. 0.2 
# 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:
			sys.__excepthook__(type, value, traceback)
	else: 
		sys.__excepthook__(type, value, traceback)

sys.excepthook = autoload_exc




More information about the Python-list mailing list