In Python, to register classes in files inside packages using decorators without explicitly loading the packages, you can use a combination of decorators and a registry to achieve this. Here’s a step-by-step guide:
Create a registry to keep track of your classes:
Instantiate the registry:
Create a decorator function to register classes:
Apply the decorator to your classes:
Automatically load modules to ensure decorators are executed:
To automatically load modules in a package and ensure that the decorators are executed, you can dynamically import all modules in the package. This can be done using the importlib library.
Access your registered classes:
Full Example
Registry Module (registry.py):
Module with Class (mypackage/mymodule.py):
Main Script to Load Modules and Access Registry:
This setup ensures that by just adding the decorators to your classes and dynamically loading the modules, the classes get registered without the need for explicit imports in your main script.