2

I have a Flask app that has the following directory structure:

    ├── README.md
    ├── __init__.py
    ├── constants.py
    ├── businesspackage
    │   ├── README.md
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── detection
    │   ├── flagging_spec.txt
    │   └── tests
    ├── requirements.txt
    ├── run.py
    └── tests
        ├── __init__.py
        ├── __pycache__
        └── test_api.py

Within detection's __init__.py, I have imported my necessary classes, so that I can import the classes from that top-level module, rather than needing to give the full path to each of the .py files inside of the module.

I am attempting to import some classes from detection from inside run.py, but am coming across the following error: when I try to run my Flask application from the top-level directory using python3 run.py:

    Traceback (most recent call last):
    File "run.py", line 9, in <module>
        from .businesspackage.detection import AdsDetection
    SystemError: Parent module '' not loaded, cannot perform relative import

After reading some other questions on here, it suggested that I change from a relative import to an absolute import. However, if I try the following import in run.py:

    from businesspackage.detection import AdsDetection

Then I can run my Flask server without the import error, however, my imports break for the nose test runner. I am running the tests using the nosetests command, with nose 1.3.7 . How can I define my imports so that they work for both the Flask server, and for my nosetests?

Edit:

businesspackage.__init__.py is the following:

    from .business_detection import BusinessDetector
orange1
  • 2,871
  • 3
  • 32
  • 58

1 Answers1

2

So for some weird reason, I managed to get the absolute imports to work after deleting the __init__.py file in the base level directory: i.e. my directory structure looks like follows:

├── README.md
├── __init__.py
├── constants.py
├── businesspackage
│   ├── README.md
│   ├── __init__.py
│   ├── __pycache__
│   ├── detection
│   ├── flagging_spec.txt
│   └── tests
├── requirements.txt
├── run.py
└── tests
    ├── __init__.py
    ├── __pycache__
    └── test_api.py

I figured I should give it a try after seeing one of the answers on here: Python imports for tests using nose - what is best practice for imports of modules above current package . So now, all of my package is using absolute imports.

Community
  • 1
  • 1
orange1
  • 2,871
  • 3
  • 32
  • 58