In my current working directory is a sub-directory cpuimlearn
, having the following structure:
$ tree cpuimlearn
cpuimlearn
├── AdaBoostM1.py
├── DECOC.py
├── DOAO.py
├── factory.py
├── FocalBoost.py
├── ImECOC.py
├── __init__.py
└── SAMME.py
0 directories, 8 files
The file factory.py
implements a class FAC
such that:
class FAC:
def __init__(self):
pass
...
So all other files import this class. For example, AdaBoostM1.py
imports the class like so:
File: AdaBoostM1.py
from factory import FAC
fac = FAC()
....
Strangely however, these files cannot import the class. For example:
$ python
Python 3.8.3 (default, Jul 2 2020, 16:21:59)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> from cpuimlearn import AdaBoostM1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/gpuimlearn/src/CPU-imLearn/cpuimlearn/AdaBoostM1.py", line 21, in <module>
from factory import FAC
ModuleNotFoundError: No module named 'factory'
>>>
As can be seen from the new __pycache__
directory created, factory.cpython-38.pyc
isn't created as we expect if the module was successfully imported.
This is strange since factory.py
is available in the direcory, and this implements FAC
class.
$ tree cpuimlearn
cpuimlearn
├── AdaBoostM1.py
├── DECOC.py
├── DOAO.py
├── factory.py
├── FocalBoost.py
├── ImECOC.py
├── __init__.py
├── __pycache__
│ ├── AdaBoostM1.cpython-38.pyc
│ └── __init__.cpython-38.pyc
└── SAMME.py
1 directory, 10 files
CodePudding user response:
As you have __init__.py
in your directory, then this directory is treated as a python package.
To import inside python package you need to use relative import
from .factory import FAC
or full name import
from cpuimlearn.factory import FAC
explanation from python documentation is here: https://docs.python.org/3/tutorial/modules.html
CodePudding user response:
factory
is not a package.
You'd need to use relative imports:
from .factory import FAC
Alternatively:
from cpuimlearn.factory import FAC