importing package contents from multiple places in PYTHONPATH

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 24 14:41:51 EDT 2008


En Mon, 24 Mar 2008 15:06:51 -0300, <joshetomlinson at gmail.com> escribió:

> Hi all,
>
> I'm new to python, and am trying to determine if it's possible to do
> the following...
>
> I have a directory structure like this, with both 'dir1' and 'dir2' in
> my PYTHONPATH
>
> dir1/
>   foo/
>     __init__.py
>     a.py
>     b.py
>
> dir2/
>   foo/
>     __init__.py
>     a.py
>     c.py
>
> I'd like to be able to:
>
> python> import foo.a, foo.b, foo.c
>
> I'd hope for package 'foo.a' to come from dir1 since it was first on
> the path, with 'foo.b' and 'foo.c' coming form dir1 and dir2
> respectively.

Yes. Note that dir2/foo/__init__.py is not used at all and it's just  
confusing. And a.py (in dir2) won't be found inside the package but any  
"import a" from c.py will import that one instead of the one at dir1.  
dir2/foo is just a "bag", not a "package" :)

> I understand that python stops once it encounters the first 'foo'
> package in PYTHONPATH, but I was wondering if there was a way around
> this.  I've had some success modifying __path__ in the foo/__init__.py
> files, but am unsure if this is the best approach.

I think it is the simplest approach, if not the only one...

> Perhaps there's a
> way to do this with import hooks?

Perhaps... But appending a single item to __path__ is simple enough to  
stop further thinking from my side :)

Anyway, why do you want to do that? Can't use a different name for  
dir2/foo, and perhaps import its modules from inside dir1/foo/__init__.py?


-- 
Gabriel Genellina




More information about the Python-list mailing list