Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you structure python code to avoid long import statements?

example directory structure and code:

root/
├─ main.py
├─ library/
│  ├─ __init__.py
│  ├─ library_code.py
│  ├─ utilities/
│  │  ├─ __init__.py
│  │  ├─ utils_one.py
│  │  ├─ utils_two.py
# main.py

import library as lb
# lb.library_code is how you would access stuff
# library/__init__.py
import [library.]library_code
import [library.]utilities
# library.utilities.__init__.py
import [library.utilities.]utils_one
import [library.utilities.]utils_two

how would you go about removing the text [inside these square brackets] on the import statements?

of course, doing this kind of structure will cause this to not be possible:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# library/utilities/utils_one.py

import library.library_code

>Solution :

The simplest is to just use a relative import. For example in utils_one.py you can do

from . import utils_two
from .utils_two import function_one

You can also use .. to go up a hierarchy just like with a file system

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading