Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add custom parsing #332

Open
Conchylicultor opened this issue Oct 16, 2024 · 2 comments
Open

How to add custom parsing #332

Conchylicultor opened this issue Oct 16, 2024 · 2 comments

Comments

@Conchylicultor
Copy link
Contributor

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
Copy link
Owner

lebrice commented Oct 18, 2024

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")

@Conchylicultor
Copy link
Contributor Author

Thank you for the answer, unfortunately in my case, neither subgroup nor choices can be used as models can be dynamically registered (user can pass arbitrary modules --cfg.model="module.to.import.MyModel"), so I do not know the exact mapping in advance. The example from my original post was simplified.

I ended up using a hack to trick simple parsing to interpret the field as a str:

@dataclasses.dataclass
class Args:
  if typing.TYPE_CHECKING:  # For static type checking
    model_cls: type[Model] = ...
  else:  # For simple parsing
    model_cls: str = Transformer

So I'm fine at the moment. Keeping this bug open in case a cleaner solution is planned but I'll also understand if this bug was closed as there's a workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants