Skip to content

Selecting subtype from union type via command line. #588

@MiguelMonteiro

Description

@MiguelMonteiro

🐛 Bug report

No way of selecting a subtype from a union type.

When adding an argument which is a union of two types there seems to be no direct way of specifying the desired type to be parsed/instantiated. This seems to be automatically detected from the argument names and values which is undesirable in scenarios where subtypes have similar arguments but different behaviors when instantiated.

To reproduce

from dataclasses import dataclass
from jsonargparse import ArgumentParser

@dataclass
class A:
    foo: int

@dataclass
class B:
    foo: int
    bar: float = 1.0


if __name__ == "__main__":
    parser = ArgumentParser(description="Example CLI", exit_on_error=False)
    parser.add_argument("--cfg", type=A | B)
    args = parser.parse_args(["--cfg.foo=1"])
    print(args)
    print(parser.instantiate_classes(args))

Expected behavior

A way of selecting the desired subtype from the command line.

Environment

  • jsonargparse version: 4.33.1
  • Python version: 3.10
  • How jsonargparse was installed: pip
  • OS: MacOS

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