当前位置: 动力学知识库 > 问答 > 编程问答 >

python - import files inside packages - Project Structure

问题描述:

I have some doubts in relation to packages structure in a python project when I make the imports

These are some conventions

python-irodsclient_API = Project Name

I've defined python packages for each file, in this case are the following:

python-irodsclient_API/config/

python-irodsclient_API/connection/

These packages are well define as a packages and not as a directories really?

I have the file python-irodsclient_API/config/config.py in which I've defined some constants about of configuration for connect with my server:

And I have the python-irodsclient_API/connection/connection.py file:

In the last or previous image (highlighted in red) .. is this the right way of import the files?

I feel the sensation of this way is not better.

I know that the "imports" should be relatives and not absolutes (for the path) and that is necessary use "." instead "*"

In my case I don't know if this can be applied in relation to the I'm doing in the graphics.

I appreciate your help and orientation

Best Regards

网友答案:

There is a good tutorial about this in the Python module docs, which explains how to refer to packages under structured folders.

Basically, from x import y, where y is a submodule name, allows you to use y.z instead of x.y.z.

网友答案:

You have 2 options here:

1) make your project a package. Since it seems like your connection and config packages are interdependent, they should be modules within the same package. To make this happens, add a __init__.py files in python-irodsclient_API folder. Now you can use relative imports to import config into connection, as they are part of the same package:

from ..config import config

The .. part means import from one level above within the package structure (similar to how .. means parent directory in Unix)

2) if you don't want to make python-irodsclient_API a package for some reason, then the second option is to add that folder to the PYTHONPATH. You can do this dynamically per Tony Yang's answer, or do this from the bash command line as followed:

export PYTHONPATH=$PYTHONPATH:/path/to/python-irodsclient_API
网友答案:

I can invoke sys module to append python-irodsclient_API path.

import sys
sys.path.append('C:\..\python-irodsclient_API')

When you operate connection.py and want to invoke config, it's able to be successful.

分享给朋友:
您可能感兴趣的文章:
随机阅读: