import and package confusion

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 30 09:33:57 CEST 2009


En Thu, 30 Apr 2009 03:04:40 -0300, alex23 <wuwei23 at gmail.com> escribió:

> On Apr 30, 1:10 pm, Dale Amon <a... at vnl.com> wrote:
>> I do not really see any other way to do what I want. If
>> there is a way to get rid of the exec in the sample code
>> I have used, I would love to know... but I can't see how
>> to import something where part of the name comes from user
>> command line input without interpreting the code via exec.
>
> Are you familiar with __import__?
>
> iotypes = ["WINGTL","VLMPC","VLM4997"]
> for iotype in iotypes:
>   packagename = "VLMLegacy." + iotype + ".Conditions"
>   classname   = iotype + "_Conditions"
>   module      = __import__(packagename)
>   cls         = getattr(module, classname)
>   # etc

(doesn't work as written, because __import__ returns the top package when  
given a dotted name)
Replace the last three lines with:

     __import__(packagename)
     module = sys.modules[packagename]
     cls = getattr(module, "Conditions")

-- 
Gabriel Genellina




More information about the Python-list mailing list