Tricky import question.

Bengt Richter bokr at oz.net
Tue Oct 25 16:05:00 EDT 2005


On 25 Oct 2005 06:39:15 -0700, "David Poundall" <david at jotax.com> wrote:

>importedfiles = {}
>for f in FileList
>  f2 = f.split('.')[0]       # strip the .py, .pyc
   importedfiles[f2] = __import__(f2).main
   # it sounds like all you want is the above (untested ;-), or
   # use __import__(f2).main() if you actually want the _result_ returned by main

Either way, you don't need the following
>  __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.
Do you want a reference to the function, or the result of calling the function?
If you want a reference to the function itself, you should leave off the () after main,
otherwise you will execute the function.

>
>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.
probably your first file is C1_Dosing.py (or some other extension after the '.')
so f2 becomes 'C1_Dosing' and s2 becomes 'C1_Dosing.main()' and you compile that
into code bound to c, and when you try to eval(c), it tries to find C1_Dosing in
the current environment, et voila! you have the error.

When confronted with mysteries such as presented by your code results, I suggest
you intruduce print statements to verify what you are assuming about what it is doing.
E.g., you could print repr(f2) after assignment, and after the __import__ if you thought
it was going to do something to f2 in the local name space, and repr(s2) after the assignment,
etc. to see if I guessed right. Or a quick line to clone for a snapshot of local varibles
at different points might be (untested)
    print '\n'.join('%15s: %s'%(k, repr(v)[:60]) for k,v in sorted(locals().items()))

>
>in this instance C1_Dosing is the first file name in the filelist.  The
>import worked, why not the compile ??
I think the compile did work. But your code didn't produce a binding for the name
'C1_Dosing' which the code c was looking for when eval(c) was called. If you wanted to
make your code work, perhaps replacing (untested)
    __import__(f2)
with
    exec '%s = __import__(f2)'%f2  # bind imported module to name specified by f2 string
might have got by the error in eval (c), but I suspect you would want to leave the () off
the .main in any case. And why go through all that rigamarole?

>
>TIA.
>
Try it both ways and report back what you found out ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list