0

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?

3
  • Why can't you just set $PYTHONPATH in the test target in your Makefile? Commented May 24, 2014 at 23:06
  • I would want to make it as seamless as possible without using any folder paths. Commented May 24, 2014 at 23:09
  • Then you are permanently and unfixably fried. Commented May 24, 2014 at 23:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I notice you don't want to use folder paths, well I suppose my answer does use folder paths in a sense. The fact is you cannot load a python module without python knowing where the module is :) You can either make the entire thing a package (my answer) or add paths, as you already know.
It uses folders but in a more seamless way. I do not have to hard-code paths or something like this. Just the 'src' which is will be on the deployment platform.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.