0
├── ledger
│   ├── __init__.py
│   ├── ledger_data.py
│   └── ledger_model.py
├── main.py
├── sscommon
│   ├── __init__.py
│   └── logging.py
└── tests
    └── test_ledger_data.py

I need to import classes from ledger_data module when running test_ledger_data.py. I currently do sys.path.append("../") in test_ledger_data.py or I have to add symbolik links to all modules being used to tests directory. Both options seem incorrect. How to do it correctly?

If I just run the file either from project root or tests directories I get error:

    from ledger.ledger_data import LedgerData
ImportError: No module named 'ledger'
1
  • 1
    create a __init__.py file inside tests/ folder and put your inputs there Commented Oct 2, 2017 at 11:59

1 Answer 1

1

You can create an __init__.py file in your folder, and import the parent dir using:

parent_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), os.pardir))
sys.append(parent_dir)

This uses os.path to find out the directory based on your file location.


Update: create the above __init__.py and reside it inside tests/ folder. Then, in your test_ledge_data.py put at the head of the file from __init__ import *; this will import everything in your init file to your module namespace.

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

3 Comments

Please clarify how do you mean to use tests then? If I run directly (as in original question) python3 test_ledger_data.py your code is not imported/run. If I run from a new python file residing in root dir it works even without this code.
Is it anything better than sys.path.append("../") ? I've read here on SO that it isn't a good practice. Will not it have side effects when doing from tests.test_ledger_data import TestLedgerData, if eventually I decide to run from some other location?
@VladimirLenin The code above imports the parent folder; so as long as the structure is kept even if you move it to some other location - it would work. If you found my answer useful, please consider upvoting and accepting it, thanks

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.