Skip to content

Improve ModelDependenciesMapping get Method in m #220

Open
@tgenin

Description

@tgenin

The Get method of ModelDependenciesMapping exhibits ambiguous behavior. Contrary to what one might expect, it is not a dictionary-like get method. Instead, it acts as a getter/caster that raises an exception when a dependency is not present. This can lead to complicated code, especially when certain configurations do not load a dependency.

For instance, instead of writing:

self.my_dependant_model = self.model_depedencies["my_dependant_model"] if "my_dependant_model" in self.model_depedencies else None

It would be more straightforward to write:

self.my_dependant_model = self.model_depedencies.get("my_dependant_model")

To improve the behavior without breaking the "cast" system, I propose the following change:

def get(
    self, key: str, model_type: Optional[Type[ModelDependency]] = None
) -> ModelDependency:
    m = self.models.get(key)
    if m is None:
        return m
    if model_type and not isinstance(m, model_type):
        raise ValueError(f"Model `{m}` is not an instance of {model_type}")
    return cast(ModelDependency, m)

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