lebrice / SimpleParsing

Simple, Elegant, Typed Argument Parsing with argparse
MIT License
401 stars 50 forks source link

Fix bug with new Union syntax with postponed type annotations #112

Closed lebrice closed 2 years ago

lebrice commented 2 years ago

This is a 'hotfix' to add a feature missing from the last release: support for annotations of this kind:

from __future__ import annotations
from dataclasses import dataclass, field

@dataclass
class Foo:
    a: int | bool = False
    c: list[int] | list[float] = field(default_factory=list)

However, beware, the second one (union of containers, as well as containers of unions) aren't yet properly supported! The current way to get this to work is to:

def _int_or_float(v: str) -> int | float:
    try:
        return int(v)
    return float(v)

@dataclass
class Foo:
    a: int | bool = False
    c: list[int] | list[float] = field(default_factory=list, type=_int_or_float)

This makes argparse use the given type for the argument.

Signed-off-by: Fabrice Normandin fabrice.normandin@gmail.com