importing classes from a variable

robin and jim robinjim at earthlink.net
Thu Jan 18 20:32:26 EST 2001


hello Justin,

Are you looking for something like the following?


import os, string, sys

directory_name = sys .argv [1]
package_name = string .replace (directory_name, os.sep, '.')

try:
   package = __import__ ( package_name, globals(), locals(), ['__init__'] )
   modules = getattr (package, '__all__')
except AttributeError, message:
   handle_error ('"__init__.py" file for ' + directory_name + ' has no
"__all__ attribute')
except ImportError, message:
   handle_error (directory_name + ' has no "__init__.py" file')


"JustinHJ" <justinhj at hotmail.com> wrote in message
news:t6f17dps6c4d87 at corp.supernews.com...
> Could anyone offer any advice on the following problem. What I have is a
> python program that takes a file and does something to it by calling
member
> functions in a class. To seperate the code that does the export from the
> main program, what I wanted to do is to be able to go from a text string
> name of the export process....
>
> str = 'export_1'
>
> and do the equivalent of
>
> import 'export_1'
>
> exportclass = export1.Export.DoExport
>
> So in case that's not clear I want to be able to import modules in a class
> without knowing their name until runtime, then use the module name as a
> variable.EG:
>
> export_string = 'export_1'
>
> import export_string # this doesn't work
>
> export_string.Export # this doesn't work either
>
>
>
>
>





More information about the Python-list mailing list