0

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

__init__.py:

# import the main module
import PKG.main

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

main.py (simplified):

import PKG.exceptions

def f(x):
    return(x+1)

exceptions.py:

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

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

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

test_basic.py:

# 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

context.py:

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

2

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 that you have read and understand our privacy policy and code of conduct.

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