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?

2
  • Look at my answer please Commented Jun 10, 2021 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. Commented Jun 10, 2021 at 12:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks for the answer, I accepted @mseromenho answer as it is more clear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.