python-3.xbuildpackagepants

Import all libraries from Python package in pantsbuild


I want to import all the resources in my models/sources directory, into another target in pants build my contents of root/models/sources:

├── base.py
├── BUILD
├── design.py
├── email.py
├── __init__.py
└── project_management.py

The contents of my build file are as follows:

python_library(
    name="base",
    sources=["base.py"],
    dependencies=["root/models/tokens/__init__.py:__init__"]
)

python_library(
    name="design",
    sources=["design.py"],
    dependencies=[":base"]
)

python_library(
    name="email",
    sources=["email.py"],
    dependencies=[":base"]
)

python_library(
    name="project_management",
    sources=["project_management.py"],
    dependencies=[
        ":base",
        "root/models/tokens/__init__.py:__init__"
    ]
)

python_library(
    name="__init__",
    sources=["__init__.py"],
    dependencies=[
        ":base",
        ":design",
        ":email",
        ":project_management"
    ]
)

Now in another target, I have an

from root.models.sources import *

How would I set up the dependencies of this other target to import all the libraries in models/sources ? p.s I know using * is not best, but that's the simplest form. Also, init is a Factory.


Solution

  • import the init as long as it's a Factory that references all the other files in the package. eg:

    from root.models.sources.base import Source
    from root.models.sources.design import DesignSource
    from root.models.sources.email import EmailSource
    from root.models.sources.project_management import \
        ProjectManagementSource
    
    
    def SourceFactory(source: str = "default"):
        sources = {
            "default": Source,
            "foo1": ProjectManagementSource,
            "foo2": ProjectManagementSource,
            "foo3": ProjectManagementSource,
            "foo4": ProjectManagementSource,
            "foo5": ProjectManagementSource,
            "foo6": ProjectManagementSource,
            "foo7": ProjectManagementSource,
            "foo8": EmailSource,
            "foo9": DesignSource,
        }
    
        return sources[source] if source in sources.keys() else Source