bgarcial
bgarcial

Reputation: 3183

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?

enter image description here

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:

enter image description here

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

enter image description here

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

Upvotes: 1

Views: 861

Answers (3)

oxymor0n
oxymor0n

Reputation: 1097

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

Upvotes: 1

Burger King
Burger King

Reputation: 2965

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.

Upvotes: 0

Iron Fist
Iron Fist

Reputation: 10951

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.

Upvotes: 1

Related Questions