Static Modules...

Chris Liechti cliechti at gmx.net
Sat Apr 17 14:01:02 EDT 2004


Grzegorz Dostatni <grzegorz at ee.ualberta.ca> wrote in
news:Pine.LNX.4.44.0404171006210.27811-100000 at e5-05.ee.ualberta.ca: 
> 
> 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?

"import this" -> "Explicit is better than implicit."

you dont easily see what exetrnal modules a program uses. that makes it 
more difficult to debug, and it makes neat things like py2exe/installer 
impossible.

a slight missconception is also there, as variables dont exist out of 
nothing, they start apearing when you assign something to them. (appart 
from that i dont like to say "variable" in python, more like binding names 
to objects.)

so something similar to using "variables" would be:

sys = __import__("sys")

which is already possible without any hack ;-)

however, it could be a nice little hack for interactive sessions when 
playing around in the interpreter. but i'd like to see a message when it 
imports something, so that later when copy&pasting something to a file, i 
dont forget the imports.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list