import and package confusion
davea at ieee.org
Thu Apr 30 08:38:03 CEST 2009
Dale Amon wrote:
> On Wed, Apr 29, 2009 at 10:02:46PM -0400, Dave Angel wrote:
>> The dot syntax works very
>> predictably, and quite flexibly. The problem was that by using the same
>> name for module and class, you didn't realize you needed to include both.
> It is one of the hazards of working in many very different
> languages. But I see where that confusion lies and that is
> a useful thing to know.
>> And in particular if you simply do the following, you can choose between
>> those modules:
>> if test:
>> mod = mymodule1
>> mod = mymodule2
>> obj = mod.myclass(arg1, arg2)
> Not really applicable to the case I have. There can be lots of
> different ones and the input selection comes from a command line
> string so...
>> Please don't sink to exec or eval to solve what is really a
>> straightforward problem.
> 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.
> [See the test module I posted.] I'm dealing with something
> like this:
> myprogram --type WINGTL file.dat
> the set of types will have new members added as they are
> discovered and I intend to minimize code changes to doing
> nothing but create a subpackage directory with the new
> modules, drop it in place. New functionality with no
> mods to the existing code...
As Scott David Daniels says, you have two built-in choices, depending on
Python version. If you can use __import__(), then realize that
mod = __import__("WINGTL")
will do an import, using a string as the import name. I don' t have the
experience to know how it deals with packages, but I believe I've heard
it does it the same as well.
One more possibility, if you're only trying to get a single package
hierarchy at a time, it might be possible to arrange them in such a way
that the sys.path search order gets you the package you want. Rather
than the top level being a package, it'd be an ordinary directory, and
you'd add it to the sys.path variable so that when you import a
subpackage (which would now really just be a package), you'd get the
More information about the Python-list