lebrice / SimpleParsing

Simple, Elegant, Typed Argument Parsing with argparse
MIT License
386 stars 47 forks source link

Add `replace_subgroups` function #215

Closed zhiruiluo closed 1 year ago

zhiruiluo commented 1 year ago

This PR is to add the replace_selections function that replaces some values in a dataclass and replaces dataclass type in nested union of dataclasses or subgroups.

simple_parsing.replace_selections function support replacingeplaces dataclass type in nested union of dataclasses or subgroups in addition to simple_parsing.replace #212.

Open question:

Examples

    >>> import dataclasses
    >>> from simple_parsing import replace_selections, subgroups
    >>> from typing import Union
    >>> @dataclasses.dataclass
    ... class A:
    ...     a: int = 0
    >>> @dataclasses.dataclass
    ... class B:
    ...     b: str = "b"
    >>> @dataclasses.dataclass
    ... class Config:
    ...     a_or_b: Union[A, B] = subgroups({'a': A, 'b': B}, default_factory=A)
    ...     a_or_b_union: Union[A, B] = dataclasses.field(default_factory=A)
    ...     a_optional: Union[A, None] = None

    >>> base_config = Config(a_or_b=A(a=1))
    # Replace subgroups field by subgroup `Key`, dataclass type, or dataclass instance
    >>> replace_selections(base_config, {"a_or_b.b": "bob"}, {"a_or_b": "b"})
    Config(a_or_b=B(b='bob'), a_or_b_union=A(a=0), a_optional=None)
    >>> replace_selections(base_config, {"a_or_b.b": "bob"}, {"a_or_b": B})
    Config(a_or_b=B(b='bob'), a_or_b_union=A(a=0), a_optional=None)
    >>> replace_selections(base_config, {}, {"a_or_b": B(b="bob")})
    Config(a_or_b=B(b='bob'), a_or_b_union=A(a=0), a_optional=None)

    # Replace union of dataclasses and optional dataclass
    >>> replace_selections(base_config, {"a_or_b_union.b": "bob"}, {"a_or_b_union": B})
    Config(a_or_b=A(a=1), a_or_b_union=B(b='bob'), a_optional=None)
    >>> replace_selections(base_config, {"a_optional.a": 10}, {"a_optional": A})
    Config(a_or_b=A(a=1), a_or_b_union=A(a=0), a_optional=A(a=10))
zhiruiluo commented 1 year ago

WIP

zhiruiluo commented 1 year ago

Hi @lebrice, Sorry for letting you wait too long.

Here is the updating:

zhiruiluo commented 1 year ago

Hi @lebrice, Here are some updates so far:

I would appreciate any further feedback or suggestions for improvement that you may have. Thank you.