Skip to content

Commit

Permalink
Fix importable class instances fail to parse and serialize (#448)
Browse files Browse the repository at this point in the history
  • Loading branch information
mauvilsa authored Feb 5, 2024
1 parent fe8bc4b commit 63444a4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ The semantic versioning only considers the public API as described in
paths are considered internals and can change in minor and patch releases.


v4.27.5 (2024-02-??)
--------------------

Fixed
^^^^^
- Importable class instances fail to parse and serialize (`#446
<https://github.com/omni-us/jsonargparse/issues/446>`__).


v4.27.4 (2024-02-01)
--------------------

Expand Down
6 changes: 6 additions & 0 deletions jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,8 @@ def adapt_typehints(

try:
val_class = import_object(resolve_class_path_by_name(typehint, val["class_path"]))
if isinstance(val_class, typehint):
return val_class
if not is_subclass(val_class, typehint):
raise_unexpected_value(
f'Import path {val["class_path"]} does not correspond to a subclass of {typehint}'
Expand Down Expand Up @@ -1242,6 +1244,10 @@ def typehint_metavar(typehint):


def serialize_class_instance(val):
with suppress(Exception):
import_path = get_import_path(val)
if import_path and import_object(import_path) is val:
return import_path
val = f"Unable to serialize instance {val}"
warning(val)
return val
Expand Down
18 changes: 18 additions & 0 deletions jsonargparse_tests/test_subclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,24 @@ def test_subclass_in_subcommand_with_global_default_config_file(parser, subparse
assert cfg.fit.model.foo == 123


# importable instances


class dtype:
pass


float32 = dtype()


def test_importable_instances(parser):
parser.add_argument("--dtype", type=dtype)
cfg = parser.parse_args([f"--dtype={__name__}.float32"])
assert cfg.dtype is float32
dump = parser.dump(cfg)
assert dump.strip() == f"dtype: {__name__}.float32"


# custom instantiation tests


Expand Down

0 comments on commit 63444a4

Please sign in to comment.