This is a matter of naming, structuring and conventions.
I am developing a simple python package. in a directory "PKG" I have 3 files:


# import the main module
import PKG.main

# in case for: from PKG import *
__all__ = [ "main" ]

main.py (simplified):

import PKG.exceptions

def f(x):


class Error(Exception):
    """Base class for other exceptions."""

class SomethingWentWrong(Error):
    """Raised when something went wrong."""

Apart from that I have a directory "tests" with two files:


# import the testing framework
import pytest

# import the package
from context import PKG

def test_simple():
    """Tests if the package is functional."""
    result = PKG.main.f(5)
    assert result==6


import os
import sys
sys.path.insert(0, os.path.abspath(
    os.path.join(os.path.dirname(__file__), '..')))

import PKG

And now I realised that both the tests and the potential user have to know that the main module of my package is called "main". I would like to omit that step, so that the user can call: PKG.f(5). What places should I adjust? What if my project would grow and there would be more modules (that are all loaded from main.py)?

1 Answer 1


Your __init__.py file should import and expose all names it want to be available in the package's top level:

# import the main module
from .main import f

# And if you want the "main" module to be 
# visible and imported automatically:

import PKG.main

Usually there is no need for an __all__ attribute. If you define any temporary setup functions or objects at module level, you can make use of it.

Also this "context.py" module seens strange. In modern Python development, your package should be available to your Python install either by issuing a python setup.py develop command or pip install -e . in the folder where your package-defining "setup.py" file is located. Check how to create a minimal setup file in the docs. Also, there are helpers like "poetry" that will generate a setup.py for you.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.