Search code examples
pythonimportcode-organization

how to organize a python module that scripts can be run as __main__ program?


I'm starting a project in python, the code structure now as below:

project/
        __init__.py
        a.py
        b.py
        mainA.py
        utilities/
                   __init__.py
                   mainB.py
                   c.py

The __init__ files are all blank.

I want to run utilities/mainB.py as a program(using something like python main.py), and mainB needs to import a.py and b.py. So I tried from .. import a and some other approaches, but the import failed. The error information is:

ValueError: Attempted relative import in non-package

So here comes the questions:

  1. how to fix mainB.py so it can be run as a main program?
  2. mainA.py can be run as main program now, it also imports a.py and b.py(using import a and import b). I think the code structure may become more complex. Say, if mainA.py has to import a module from project/some/directory, how can I do that?

Solution

  • You could use Python's built-in module-running functionality (python -m <module>).

    python -m project.utilities.mainB
    

    This allows you to write mainB normally as part of the package, so relative and absolute imports will both work correctly.

    For an in-depth discussion of this functionality, see PEP-338.