Possible cleanup of "Options" boilerplate #402

Merged
telackey merged 2 commits from erikdies/cli_ergonomics_alternatives into main 2023-05-25 00:02:25 +00:00
Contributor

Maybe this is a little cleaner using dataclasses?

The dataclass decorator is doing the same thing you are here with __init__, but also adds __repr__ and __eq__ by default. The args can be passed positionally or as kwargs by default, with a kwargs only option. The dataclass also allows for some nice things like setting defaults that would be challenging with regular classes.
re: https://docs.python.org/3/library/dataclasses.html

You can also get some features that might be desirable (not used in this PR), like fake immutability using the kwarg "frozen"

@dataclass(frozen=True)
class DataExample:
    foo: int
    bar: bool
    
>> ex = DataExample(4, True)
>> print(ex)
 DataExample(foo=4, bar=True)
 
>> ex.foo = 5
---------------------------------------------------------------------------
FrozenInstanceError                       Traceback (most recent call last)
Cell In[19], line 1
----> 1 ex.foo = 5

File <string>:4, in __setattr__(self, name, value)

FrozenInstanceError: cannot assign to field 'foo'
Maybe this is a little cleaner using dataclasses? The dataclass decorator is doing the same thing you are here with `__init__`, but also adds `__repr__` and `__eq__` by default. The args can be passed positionally or as kwargs by default, with a kwargs only option. The dataclass also allows for some nice things like setting defaults that would be challenging with regular classes. re: https://docs.python.org/3/library/dataclasses.html You can also get some features that might be desirable (_not used in this PR_), like fake immutability using the kwarg "frozen" ``` @dataclass(frozen=True) class DataExample: foo: int bar: bool >> ex = DataExample(4, True) >> print(ex) DataExample(foo=4, bar=True) >> ex.foo = 5 --------------------------------------------------------------------------- FrozenInstanceError Traceback (most recent call last) Cell In[19], line 1 ----> 1 ex.foo = 5 File <string>:4, in __setattr__(self, name, value) FrozenInstanceError: cannot assign to field 'foo' ```
Author
Contributor

Setting defaults here is not needed, just done to match the defaults in the CLI tooling to replicate defaults for repl use.

Setting defaults here is not needed, just done to match the defaults in the CLI tooling to replicate defaults for repl use.
dboreham left a comment
Contributor

Thanks!

Thanks!
This repo is archived. You cannot comment on pull requests.
No Reviewers
2 Participants
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: cerc-io/stack-orchestrator#402