Skip to content

Option to fail on failure to initialize classes #271

@JoostvDoorn

Description

@JoostvDoorn

🚀 Feature request

Add an option to fail on class initialization.

Motivation

Currently if a config contains a class_path with init_args, and it fails to initialize the class it will ignore the error, and just return a dict/namespace. If the class contains a error it's unclear what the issue is requiring the user to use a debugger or to test it outside of the script that uses jsonargparse.

See the code (on line 1054-1055 any exception is ignored):

if is_subclass_spec(val):
orig_val = val
val = subclass_spec_as_namespace(val)
init_args = val.get('init_args')
if init_args and not instantiate_classes:
for subkey, subval in init_args.__dict__.items():
init_args[subkey] = adapt_classes_any(subval, serialize, instantiate_classes, sub_add_kwargs)
val['init_args'] = init_args
try:
val = adapt_class_type(val, serialize, instantiate_classes, sub_add_kwargs)
except Exception:
return orig_val

Note: I am not aware of the full impact, and I think it's possible that simply raising this exception always is not enough as it might fail too often as well in valid use cases. E.g. check_values in

raise KeyError(f'No action for destination key "{key}" to check its value.')
raises an exception for a case which I think is valid.

Pitch

I would like to have an option to fail in cases where initializing a class fails, and raise the exception of the underlying code.

Alternatives

An alternative is to fail always, but this could be considered a breaking change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions