Search code examples
pythonimportpackagedirectory-structurefile-structure

How do I decrease the length of imports for my custom package?


I have a package called "library". The directory structure looks like this:

-library

    +src

        *pkg1.py

        *pkg2.py

-pyproject.toml

-__init__.py

Currently, the import looks like:

import library.src.pkg1 as pkg1

The pyproject.toml contains:

[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

[project]
name = "library"
version = "0.0.1"
dependencies = []

How do I make it so that the import is shorter? Ideally:

import library.pkg1


Solution

  • In the library/init.py file, you can import the modules from the src subpackage and expose them at the package level. This way, when users import library.pkg1, it will internally reference library.src.pkg1.

    Update library/init.py like this:

    from .src.pkg1 import *
    from .src.pkg2 import *
    

    This makes all the contents of pkg1.py and pkg2.py available directly under library.

    Usage:

    Now, you can import the modules like this:

    import library.pkg1
    import library.pkg2
    

    or directly import specific items from those modules:

    from library.pkg1 import SomeClassOrFunction
    from library.pkg2 import AnotherClassOrFunction