简体   繁体   中英

Python: How to import sub-modules, from packages with the same name?

I have a project setup looks like this:

Base project

/some_disk/some_folder/
|-- project/
|   |-- package/
|   |   |-- src/
|   |   |   |-- file_a.py
|   |   |   |-- file_b.py

Extension project

/some_other_disk/some_folder/
|-- project/
|   |-- package/
|   |   |-- src/
|   |   |   |-- file_c.py
|   |   |   |-- file_d.py

Then I have a third project, in which I would like to be able to use both mopdules file_a and file_c.

In that third project, I have setup my Python path like this

PYTHONPATH=$PYTHONPATH:/some_disk/some_folder:/some_other_disk/some_folder

Then, to import the files, I have this in my main module:

import project.module.src.file_a
import project.module.src.file_c

This, however, only makes me able to import one of the modules, and having an module not found error on the other one.

Can I make this work using this project structure? Or will Python always only look into one of the "main"-modules and consider the sub-module not found if it's not in there?

EDIT: The project makes use of Python 2.6

Create a package file __init__.py in each of your src directories. They should contain the following two lines. See this documentation for details. This solution works on Python 2.6 and is the canonical solution.

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

This will make python search in your current directory/standard directories first, and for the second one, python will search in your pathtofile_c first before standard directories.

import project.module.src.file_a  #<--- here it searches some_disk first
sys.path.insert(0,'pathtofile_c') #<--- Changes your PYTHONPATH - inserts some_other_disk before standard directories
import project.module.src.file_c  #<--- here it searches some_other_disk first

This should clear python's confusion.

You need to have __init__.py files within those directories to make python treat then as a package instead of plain directories.

Refer to this discussion to learn more about init .py files.

Note:I have edited my previous answer by removing the irrelevant content based on the discussion with the poster of the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM