faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

from (some module) import *

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 250, Tim Evans


"""
Packages: modules_and_packages
"""
"""
> 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.
"""