from (some module) import *

Tim Evans tre17 at student.canterbury.ac.nz
Wed Oct 27 19:00:00 EDT 1999


Ed <elb at cfdrc.com> writes:

> I'm new to Python, I hope I'm not trying to do the wrong thing here, but
> pls correct me if I am:
> 
> I want to prompt for a module name, then import it.  How do I make the
> module name in the "from" or "import" operators a variable?  I was
> trying
> 
> print "enter the file name"
> filename = raw_input()
> from filename import *
> 
> This "module" I'm hoping to import contains only a list, Data = [...],
> and I have lots of such modules to process - each with different values
> in the Data list - and it changes all the time.  I thought I could
> change my script to prompt for the file/module name rather than edit the
> script each time I wanted to process a different file/module.

This function will do what you want:


def importhack(name):
    mod = __import__(name)
    g = globals()
    for var in dir(mod):
        if var[0] != '_':
            g[var] = getattr(mod, var)


Whether or not you actually want to do this is another question.  I
would guess that it is probably a bad idea, but could be useful
anyway.

--
Tim Evans





More information about the Python-list mailing list