Maltimore
Maltimore

Reputation: 514

Elevate python subpackage with importlib

I have a package with subpackages. When importing package I want to dynamically make one of the subpackages available as a fixed name. How do I do this?

/package
    __init__.py
    /subpackage1
        __init__.py
    /subpackage2
        __init__.py

From the outside I would like to be able to do from package import subpackage, and the __init__.py in package makes the correct subpackage (1 or 2) available as package.subpackage depending on an environment variable.

edit: I specifically want to use importlib.import_module() to do this, because I need to put together a string that gives the path to the subpackage.

Upvotes: 1

Views: 345

Answers (1)

javidcf
javidcf

Reputation: 59731

You just need to import the correct subpackage in package/__init__.py as subpackage.

import importlib
import os

if os.environ.get('MY_ENV_VAR', None):  # Check your env condition here
    pkg = '.subpackage1'
else:
    pkg = '.subpackage2'
subpackage = importlib.import_module(pkg, __name__)

Upvotes: 1

Related Questions