Tricky import question.

Fredrik Lundh fredrik at pythonware.com
Tue Oct 25 10:04:34 EDT 2005


David Poundall wrote:

> importedfiles = {}
> for f in FileList
>  f2 = f.split('.')[0]       # strip the .py, .pyc
>  __import__(f2)
>  s2 = f2+'.main()'          # main is the top file in each import
>  c = compile(s2, '', 'eval')
>  importedfiles[f2] =  eval(c)
>
> 'importedfiles' should hold an object reference to the main() function
> within each imported file.
>
> The problem is, the import function works but I can't get the object
> reference into the imortedfiles dictionary object.  the code keeps
> telling me
>
> NameError: name 'C1_Dosing' is not defined.
>
> in this instance C1_Dosing is the first file name in the filelist.  The
> import worked, why not the compile ??

because your __import__ statement didn't assign the returned module
to anything, so there's no C1_Dosing in the current namespace.

assuming that the main function in each module returns something that
you want to store in the importedfiles dictionary, here's a better way to
do it:

    m = __import__(f2)
    importedfiles[f2] =  getattr(m, "main")()

tweak as necessary.

</F> 






More information about the Python-list mailing list