3

I am currently constructing a custom module with an architecture like such:

module/
│
├── util/
│   ├── metrics.py
│   └── util.py
│
└── training/
    ├── pretraining.py
    └── training_step.py

In my pretraining.py script I need to use a function located in util.py. I am not sure how to import it in pretraining.py

So far I tried the classic:

from util.metrics import accuracy

I get the following error:

Traceback (most recent call last):
  File "pretraining.py", line 5, in <module>
    from util.metrics import accuracy
ModuleNotFoundError: No module named 'util'

How can I import the function in pretraining.py?

arnino
  • 441
  • 2
  • 14
  • Look at my answer please – PCM Jun 10 '21 at 10:22
  • @arnino I just added some references on my answer, maybe it can contribute for a better understanding on how packages work in Python. Thanks for the accepting my answer as the more clear. – mseromenho Jun 10 '21 at 12:53

2 Answers2

4

As PCM indicated you have to create an empty __init__.py file inside each folder:

module/
├── __init__.py
│
├── util/
│   ├──__init__.py
│   ├── metrics.py
│   └── util.py
│
└── training/
    ├──__init__.py
    ├── pretraining.py
    └── training_step.py

So if in your pretraining.py script you need to use a function located in util/metrics.py:

from module.util.metrics import accuracy

Some references:

https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/06-Modules%20and%20Packages/Useful_Info_Notebook.ipynb

https://docs.python.org/3/tutorial/modules.html#packages

https://python4astronomers.github.io/installation/packages.html

mseromenho
  • 163
  • 7
1

Clearly, you are trying to import from another folder. For that, you need to make it a package

You need to save an empty __init__.py file in the module folder, and subfolders. __init__.py will make it a package, so you can import it using from util.metrics import accuracy

PCM
  • 2,881
  • 2
  • 8
  • 30