Skip to content
Advertisement

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:

# library/utilities/utils_one.py

import library.library_code

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement