lebrice / SimpleParsing

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

[Feature Request] Add `replace` API similar to dataclasses.replace #198

Closed zhiruiluo closed 1 year ago

zhiruiluo commented 1 year ago

Is your feature request related to a problem? Please describe. The replace function of the dataclasses module has the signature of Dataclasses.replace(obj, /, **changes):

However, the Dataclass.replace doesn't work with nested dataclasses, subgroups, and other features in simple-parsing. To solve this, the simple_parsing.replace should be supplemented as an extension to dataclasses.replace.

Describe the solution you'd like We can use the parse API to implement this feature.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context With simple_parsing.replace, we can make this example work.

import simple_parsing as sp

@dataclass
class InnerClass:
    arg1: int = 0
    arg2: str = "foo"

@dataclass(frozen=True)
class OuterClass:
    outarg: int = 1
    nested: InnerClass = InnerClass()

changes_1 = {"outarg": 2, "nested.arg1": 1, "nested.arg2": "bar"}
changes_2 = {"outarg": 2, "nested": {"arg1": 1, "arg2": "bar"}}
c = OuterClass()
c1 = sp.replace(c, changes_1)
c2 = sp.replace(c, changes_2)
assert c1 == c2
assert c1.outarg == 2
assert c1.nested.arg1 == 1
assert c1.nested.arg2 == "bar"
zhiruiluo commented 1 year ago

I have proposed a PR #197 to this feature request.

lebrice commented 1 year ago

Hey there @zhiruiluo , the feature is already implemented here: https://github.com/lebrice/SimpleParsing/blob/master/simple_parsing/helpers/hparams/hyperparameters.py#L200

It could be moved somewhere else and made more broadly available. I'll take a look at your PR and I'll add any comments there, then come back here after.

zhiruiluo commented 1 year ago

simple_parsing.replace has been merged in #212