Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Fixed
<https://github.com/omni-us/jsonargparse/pull/818>`__).
- ``default_config_files`` with settings for multiple subcommands not working
correctly (`#819 <https://github.com/omni-us/jsonargparse/pull/819>`__).
- ``register_type`` not checking that the given type is a class (`#820
<https://github.com/omni-us/jsonargparse/pull/820>`__).

Changed
^^^^^^^
Expand Down
6 changes: 4 additions & 2 deletions jsonargparse/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ def deserializer(self, value):


def register_type(
type_class: Any,
type_class: type,
serializer: Callable = str,
deserializer: Optional[Callable] = None,
deserializer_exceptions: Union[type[Exception], tuple[type[Exception], ...]] = (
Expand All @@ -324,14 +324,16 @@ def register_type(
"""Registers a new type for use in jsonargparse parsers.

Args:
type_class: The type object to be registered.
type_class: The class to be registered.
serializer: Function that converts an instance of the class to a basic type.
deserializer: Function that converts a basic type to an instance of the class. Default instantiates type_class.
deserializer_exceptions: Exceptions that deserializer raises when it fails.
type_check: Function to check if a value is of type_class. Gets as arguments the value and type_class.
fail_already_registered: Whether to fail if type has already been registered.
uniqueness_key: Key to determine uniqueness of type.
"""
if not inspect.isclass(type_class):
raise ValueError(f"Expected type_class to be a class, got {type_class!r}")
type_handler = RegisteredType(type_class, serializer, deserializer, deserializer_exceptions, type_check)
fail_already_registered = globals().get("_fail_already_registered", fail_already_registered)
if not uniqueness_key and fail_already_registered and get_registered_type(type_class):
Expand Down
8 changes: 8 additions & 0 deletions jsonargparse_tests/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,14 @@ def deserializer(v):
pytest.raises(ValueError, lambda: register_type(datetime)) # different registration not okay


def test_register_not_a_class_type_failure():
class SomeClass:
pass

with pytest.raises(ValueError, match="Expected type_class to be a class"):
register_type(Union[SomeClass, int])


class RegisterOnFirstUse:
pass

Expand Down
Loading