-1

I am trying to find the best practice for importing modules dynamically. I have multiple files in a specific folder called providers which contain a class Updater and all of them have the same objects.

This is the structure I have:

main.py
|-providers:
  --__init__.py
  --plex.py
  --pihole.py

Each provider has 3 class objects: get_latest_version, get_current_version, install.

This is the contents of main.py file:

#!/usr/bin/env python3
from Updater.plex import Updater as PlexUpdater
from Updater.pihole import Updater as PiholeUpdater

for provClass in [PlexUpdater, PiholeUpdater]:
    provider = provClass()
    latest_version = provider.get_latest_version()
    current_version = provider.get_current_version()
    provider.install()

I need to be able to create file on the providers folder and be automatically imported on the main file without explicitly importing myself. Could you suggest a way to make this work?

1 Answer 1

2

I finally found how to do this. On the init file I loaded all modules and returned them as a dictionary.

Code for __init__.py:

from pkgutil import iter_modules
from pathlib import Path
from importlib import import_module

globals()['modules'] = {}

# iterate through the modules in the current package
package_dir = Path(__file__).resolve().parent
for (_, module_name, _) in iter_modules([package_dir]):
    globals()['modules'][module_name] = getattr(import_module(f"{__name__}.{module_name}"), 'Updater')

The main.py changed into this:

#!/usr/bin/env python3
import providers

for provider_name, module in providers.modules.items():
    provider = module()
    latest_version = provider.get_latest_version()
    current_version = provider.get_current_version()
    provider.install()

Most helpful article was this.

2
  • 1
    Note that you don't need globals(). You could just do modules = {} and modules[module_name] = .... Commented Oct 24, 2020 at 22:29
  • Oh yeah. You are right. Thanks for pointing that out. Commented Oct 24, 2020 at 23:03

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.