How to import a module, which imports another module, from two different folders inside a package

Viewed 44

Assuming I have a python package with the following structure:

folder1
   __init__.py
   main.py
   subfolder1
      __init__.py
      submain.py
      subagent.py (contains class Agent)
      subnetwork.py (contains class Network)

In the subagent.py file I import the Network class and in main.py and submain.py I import the Agent class. I would like to be able to start my program from both main.py and submain.py. However this causes problem in the subagent.py file. If I start from main.py I have to write the imports in subagent.py like that:

from subfolder1.subnetwork import Network 

However if I start from submain.py I have to write the imports in subagent.py like that:

from subnetwork import Network 

Is there an elegant solution to tackle this problem?

3 Answers

Use absolute imports, i.e. starting with folder1: from folder1 import ... or import folder1. Call your mains like so: python -m folder1.main and python -m folder1.subfolder1.submain.

You can use try except blocks to import both ways

try:
    from subnetwork import Network
except ModuleNotFoundError:
    from subfolder1.subnetwork import Network 

Change the working directory?

import os

if __name__ == "__main__":  # Only change the working directory if the file is run directly
    os.chdir('..') # Move up a level so that it is the same as main
# now run the imports
Related