0

I am starting a Python project, and I have structured my code in packages and sub-packages in the following way:

FCM
|-- definitions
|   |-- Classifiers
|   |-- __init__.py
|   `-- triggers
|       |-- __init__.py
|       |-- probability.py
|-- examples
|   |-- __init__.py
|   |-- compute
|   `-- study
`-- source
    |-- __init__.py
    |-- FastComposedModels_pb2.py
    |-- genetic_algorithm
    `-- trigger_evaluator.py

Module imports between sub-packages work, however when I try to import the triggers subpackage from inside ./examples or ./source:

import definitions.triggers

I get this error:

ModuleNotFoundError: No module named 'definitions.triggers'

Here's the sys.path variable value:

/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages
/home/projects/FCM
/apps/PYTHON/3.6.1/INTEL/lib/python36.zip
/apps/PYTHON/3.6.1/INTEL/lib/python3.6
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/lib-dynload
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/pytz-2017.2-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/packaging-16.8-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/appdirs-1.4.3-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/cycler-0.10.0-py3.6.egg
/apps/PYTHON/3.6.1/INTEL/lib/python3.6/site-packages/nose-1.3.7-py3.6.e

I am using Python 3.6.1 in Linux, however, this does not happen to me in any other platform and python version. I do not understand why I can't find the triggers sub-package. Do I miss something?

Marc Ortiz
  • 2,242
  • 5
  • 27
  • 46

2 Answers2

0

It seems that there was already a "definitions" module in my python version.

Below are the steps I followed. First I imported the definitions module. Then I printed the modules loaded. And finally, I realized that the path to the package/module was not consistent to where my project was located.

import definitions
import sys
print('\n'.join(sys.modules))

It outputs:

...
source.genetic_algorithm
definitions

Then you can get the location of the module by doing:

print(sys.modules['definitions'])
Marc Ortiz
  • 2,242
  • 5
  • 27
  • 46
-1

You're trying to do a relative import, which requires a leading period ('.') character. Try

from .definitions.triggers import <function>

More details at The Python Import System docs.

sevenr
  • 379
  • 3
  • 7
  • I think I am doing an absolute import. I am importing the modules as if I was located at the root directory (FCM) – Marc Ortiz Jun 08 '20 at 16:30
  • That won't work in this context; you have to do a relative import. – sevenr Jun 08 '20 at 16:32
  • This thread answers that question: https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time. See BrenBam's answer. – sevenr Jun 08 '20 at 16:44