lebrice / SimpleParsing

Simple, Elegant, Typed Argument Parsing with argparse
MIT License
423 stars 52 forks source link

How to add custom parsing #332

Open Conchylicultor opened 4 days ago

Conchylicultor commented 4 days ago

I have a code like:

@dataclasses.dataclass
class Args:
  model_cls: type[Model] = Transformer

I would like to support this through CLI. I have a mapping str -> type[Model], such as the user can pass a string --model_cls=Transformer that I can then normalize to the model class.

Something like:

@dataclasses.dataclass
class Args:
  model_cls: type[Model] = field(default=Transformer, parsing_type=str)

  def __post_init__(self):
    if isinstance(self.model_cls, str):
      self.model_cls = _NAME_TO_CLS[self.model]

However I do not know how to make simple_parsing parse model_cls as a str.

lebrice commented 1 day ago

Hi @Conchylicultor , thanks for posting!

I suggest you take a look at the subgroups feature

Otherwise you can also have a field with simple_parsing.field(choices=dict_with_str_to_models.keys(), default="transformer")