Exemplo n.º 1
0
Arquivo: plugins.py Projeto: wpc/hydra
    def _instantiate(self, config: DictConfig) -> Plugin:
        from hydra._internal import utils as internal_utils

        classname = internal_utils._get_cls_name(config, pop=False)
        try:
            if classname is None:
                raise ImportError("class not configured")

            if not self.is_in_toplevel_plugins_module(classname):
                # All plugins must be defined inside the approved top level modules.
                # For plugins outside of hydra-core, the approved module is hydra_plugins.
                raise RuntimeError(
                    f"Invalid plugin '{classname}': not the hydra_plugins package"
                )

            if classname not in self.class_name_to_class.keys():
                raise RuntimeError(f"Unknown plugin class : '{classname}'")
            clazz = self.class_name_to_class[classname]
            plugin = internal_utils._instantiate_class(clazz=clazz,
                                                       config=config)
            assert isinstance(plugin, Plugin)

        except ImportError as e:
            raise ImportError(
                f"Could not instantiate plugin {classname} : {str(e)}\n\n\tIS THE PLUGIN INSTALLED?\n\n"
            )

        return plugin
Exemplo n.º 2
0
def test_get_class_name(config: DictConfig, expected: Any, warning: Any,
                        recwarn: Any) -> None:
    assert utils._get_cls_name(config) == expected

    target_field_deprecated = (
        "\nConfig key '{key}' is deprecated since Hydra 1.0 and will be removed in Hydra 1.1."
        "\nUse '_target_' instead of '{field}'."
        "\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/object_instantiation_changes"
    )

    if warning is not False:
        assert recwarn[0].category == UserWarning
        assert recwarn[0].message.args[0] == target_field_deprecated.format(
            key=warning, field=warning)
Exemplo n.º 3
0
def test_get_class_name(config: Union[ObjectConf, DictConfig], expected: Any,
                        warning: Any, recwarn: Any) -> None:
    assert utils._get_cls_name(config) == expected
    if warning is not False:
        deprecated = "is deprecated since Hydra 1.0 and will be removed in Hydra 1.1"
        if isinstance(config, DictConfig):
            exp = f"""Config key '{config._get_full_key(warning)}' {deprecated}.
Use 'target' instead of '{warning}'."""
        else:
            exp = f"""
ObjectConf field '{warning}' {deprecated}.
Use 'target' instead of '{warning}'."""

        assert len(recwarn) == 1
        assert recwarn[0].category == UserWarning
        assert recwarn[0].message.args[0] == exp
Exemplo n.º 4
0
Arquivo: utils.py Projeto: wpc/hydra
def call(config: Any, *args: Any, **kwargs: Any) -> Any:
    """
    :param config: An object describing what to call and what params to use.
                   Must have a _target_ field.
    :param args: optional positional parameters pass-through
    :param kwargs: optional named parameters pass-through
    :return: the return value from the specified class or method
    """

    if OmegaConf.is_none(config):
        return None

    if isinstance(config, TargetConf) and config._target_ == "???":
        # Specific check to give a good warning about failure to annotate _target_ as a string.
        raise InstantiationException(
            f"Missing value for {type(config).__name__}._target_. Check that it's properly annotated and overridden."
            f"\nA common problem is forgetting to annotate _target_ as a string : '_target_: str = ...'"
        )

    if not (isinstance(config, dict) or OmegaConf.is_config(config)
            or is_structured_config(config)):
        raise HydraException(
            f"Unsupported config type : {type(config).__name__}")

    # make a copy to ensure we do not change the provided object
    config_copy = OmegaConf.structured(config)
    if OmegaConf.is_config(config):
        config_copy._set_parent(config._get_parent())
    config = config_copy

    cls = "<unknown>"
    try:
        assert isinstance(config, DictConfig)
        OmegaConf.set_readonly(config, False)
        OmegaConf.set_struct(config, False)
        cls = _get_cls_name(config)
        type_or_callable = _locate(cls)
        if isinstance(type_or_callable, type):
            return _instantiate_class(type_or_callable, config, *args,
                                      **kwargs)
        else:
            assert callable(type_or_callable)
            return _call_callable(type_or_callable, config, *args, **kwargs)
    except InstantiationException as e:
        raise e
    except Exception as e:
        raise HydraException(f"Error calling '{cls}' : {e}") from e
Exemplo n.º 5
0
def call(config: Union[ObjectConf, DictConfig], *args: Any, **kwargs: Any) -> Any:
    """
    :param config: An ObjectConf or DictConfig describing what to call and what params to use
    :param args: optional positional parameters pass-through
    :param kwargs: optional named parameters pass-through
    :return: the return value from the specified class or method
    """
    if OmegaConf.is_none(config):
        return None
    try:
        cls = _get_cls_name(config)
        type_or_callable = _locate(cls)
        if isinstance(type_or_callable, type):
            return _instantiate_class(type_or_callable, config, *args, **kwargs)
        else:
            assert callable(type_or_callable)
            return _call_callable(type_or_callable, config, *args, **kwargs)
    except Exception as e:
        raise HydraException(f"Error calling '{cls}' : {e}") from e
Exemplo n.º 6
0
def call(
    config: Union[ObjectConf, TargetConf, DictConfig, Dict[Any, Any]],
    *args: Any,
    **kwargs: Any,
) -> Any:
    """
    :param config: An object describing what to call and what params to use
    :param args: optional positional parameters pass-through
    :param kwargs: optional named parameters pass-through
    :return: the return value from the specified class or method
    """
    if isinstance(config, TargetConf) and config._target_ == "???":
        raise InstantiationException(
            f"Missing _target_ value. Check that you specified it in '{type(config).__name__}'"
            f" and that the type annotation is correct: '_target_: str = ...'")
    if isinstance(config, (dict, ObjectConf, TargetConf)):
        config = OmegaConf.structured(config)

    if OmegaConf.is_none(config):
        return None
    cls = "<unknown>"
    try:
        assert isinstance(config, DictConfig)
        # make a copy to ensure we do not change the provided object
        config = copy.deepcopy(config)
        OmegaConf.set_readonly(config, False)
        OmegaConf.set_struct(config, False)
        cls = _get_cls_name(config)
        type_or_callable = _locate(cls)
        if isinstance(type_or_callable, type):
            return _instantiate_class(type_or_callable, config, *args,
                                      **kwargs)
        else:
            assert callable(type_or_callable)
            return _call_callable(type_or_callable, config, *args, **kwargs)
    except InstantiationException as e:
        raise e
    except Exception as e:
        raise HydraException(f"Error calling '{cls}' : {e}") from e
Exemplo n.º 7
0
def test_get_class_name(config: DictConfig, expected: Any) -> None:
    assert utils._get_cls_name(config) == expected
Exemplo n.º 8
0
def test_cls() -> None:
    with pytest.warns(expected_warning=UserWarning):
        assert utils._get_cls_name(ObjectConf(cls="foo")) == "foo"
    with pytest.warns(expected_warning=UserWarning):
        assert utils._get_cls_name(ObjectConf(cls="foo",
                                              target="bar")) == "bar"