Load three different modules which have the same name

Carsten Haese carsten at uniqsys.com
Mon Mar 19 15:06:24 EDT 2007


On Mon, 2007-03-19 at 11:42 -0700, abcd wrote:
> nevermind this took care of it:
> 
> import sys
> 
> def tryAllThree():
>     a = "c:\\alpha"
>     b = "c:\\beta"
>     g = "c:\\gamma"
> 
>     sys.path.append(a)
>     import Person
>     alpha = Person.Person()
> 
>     sys.path.remove(a)
>     sys.path.append(b)
>     reload(Person)
>     beta = Person.Person()
> 
>     sys.path.remove(b)
>     sys.path.append(g)
>     reload(Person)
>     gamma = Person.Person()

That sort of works, but it's really unclean.

I suggest you turn each directory that contains an implementation of
Person into a package. That can be done by simply putting an __init__.py
file into each of those directories. This __init__.py file can be empty
or only contain a "pass" statement, but as long as it's there, the
directory containing it becomes a package.

Then, add the directory that contains your packages (C:\ in your
example) to your path, and you can import and use your Person modules
like this:

    import alpha.Person, beta.Person, gamma.Person
    alpha_person = alpha.Person.Person()
    beta_person = beta.Person.Person()
    gamma_person = gamma.Person.Person()

The main advantages are that the different implementations of Person
don't shadow each other in your name space, and you don't gratuitously
force module reloads.

Hope this helps,

Carsten.





More information about the Python-list mailing list