Skip to content

Autodiscovery system for models #172

@davidorme

Description

@davidorme

Is your feature request related to a problem? Please describe.

It isn't ideal that we need to remember to add models and schema to virtual_rainforest.__init__.py. We have to do that to get the objects imported and to populate the model and schema registries.

Describe the solution you'd like

We can instead put this in the base __init_.py:

import importlib.metadata
from importlib import import_module
import pkgutil

# Autodiscover models in the models module
import virtual_rainforest.models as vfm

for module_info in pkgutil.iter_modules(vfm.__path__):
    import_module(f"virtual_rainforest.models.{module_info.name}")

__version__ = importlib.metadata.version("virtual_rainforest")

Then we need to consistently:

  • register model schema in virtual_rainforest/models/modelname/__init__.py (which we already do)
  • in that model __init__.py file, also import the BaseClass subclass:
from virtual_rainforest.models.modelname.modelname_model import ModelName   # noqa: F401

The import_module function then imports the members defined in __init__.py and, hey presto, everything is registered.

What this doesn't work for is when a user has a custom model outside of the virtual_rainforest package structure. At the Python command line , you could simply import vr and then from mymodule import EarthquakeModel, but that doesn't currently fit into the command line configuration: you can't simply include an earthquake model config and expect it to work. So we probably need some kind of configuration option for custom models (rather than forcing people to put their code into the pip installed package location).

But that's a way off in the distance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions