On Tue, Sep 09, 2003 at 09:35:30PM +0200, Marco Herrn wrote: > I am writing a program that has to instantiate a class from which I > don't know the name until runtime. That leads to two problems for me. > > 1. How to do the import? I didn't find a way to give a string to the > import statement. exec("import %s" % modulename) ? > 2. How to write such code to instantiate? class = getattr(modulename, classname) or class = globals()[classname] and then: an_instance = class() Although this all seems really dirty to me. Maybe there are better ways to do it. > Is it possible to say 'import * from subdirectory' ? If the directory is a python package (has an __init__.py), then you can do 'from directoryname import *' -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org The one good thing about repeating your mistakes is that you know when to cringe.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4