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?
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://docs.python.org/3/tutorial/modules.html#packages
https://python4astronomers.github.io/installation/packages.html
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.