importing package contents from multiple places in PYTHONPATH

J

joshetomlinson

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.

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. Perhaps there's a
way to do this with import hooks?

Is there a precedent for this type of thing?

Thanks in advance,
Josh
 
G

Gabriel Genellina

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top