Ungureanu Vlad
Ungureanu Vlad

Reputation: 3

Python module import issue subdir

I have the following directory structure in my Python3 project:

├── README.md
├── requirements.txt
├── schemas
│   ├── collector.sql
│   └── controller.sql
├── src
│   ├── controller.db
│   ├── controller.py
│   ├── measurement_agent.py
├── tests
│   ├── regression.py
│   ├── test-invalid-mac.py
│   ├── test-invalid-url.py
│   ├── test-register-ma-json.py
│   ├── test-register-ma-return-code.py
│   ├── test-send-capabilities-return-code.py
│   ├── test-valid-mac.py
│   └── test-valid-url.py
└── todo

In my tests folder I have some regression tests which are ran to check the consistency of the code from src/measurement_agent.py. The problem now is that I do not want to add to my path manually the measurement_agent.py to make an import from it. I would want to know if there is any trick how to tell Python to look in my root for the import I am trying to use.

Currently I am doing:

import os.path

ma = os.path.abspath('..') + '/src'
sys.path.append(ma)

from measurement_agent import check_hardware_address

and would want to have something just like

from measurement_agent import check_hardware_address

without using any os.path tricks.

Any suggestions?

Upvotes: 0

Views: 103

Answers (1)

Henry
Henry

Reputation: 6620

Relative imports

  1. Make sure there is an __init__.py in all folders including the top-most (the parent)
  2. Use a relative import, like this:

    from ..src import measurement_agent

  3. Now to run your code, cd up to the parent of your parent directory and then

    python -m parent.test.regression

Upvotes: 1

Related Questions