omni-us / jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
https://jsonargparse.readthedocs.io
MIT License
302 stars 41 forks source link

`CLI` fails to instantiate `pydantic` classes #503

Closed rusmux closed 1 month ago

rusmux commented 2 months ago

🐛 Bug report

CLI fails to instantiate pydantic classes.

To reproduce

In main.py:

import jsonargparse
import pydantic

class MyClass1(pydantic.BaseModel):
    a: int

class MyClass2(pydantic.BaseModel):
    b: int

def func(instance: pydantic.BaseModel) -> None:
    print(instance)

if __name__ == "__main__":
    jsonargparse.CLI(func)

In config.yaml:

instance:
  class_path: __main__.MyClass1
  init_args:
    a: 1

In terminal:

python -m main --config config.yaml

Expected behavior

Program should exit with zero code.

It does work If I change pydantic classes to normal classes.

Environment

mauvilsa commented 2 months ago

Thank you for reporting!

This is not a bug. Pydantic classes behave like dataclasses, which means, they don't behave like subclasses and don't accept class_path to select a derived class. This could be considered a duplicate of #287, since the fix will be the same: a new feature that allows developers to select which classes and which not behave as subclasses.

Running the reproduction code, I do see a bug. The parsing is not failing with an error saying class_path and init_args are unexpected. Which is why the failure is on instantiation making it misleading.

mauvilsa commented 1 month ago

Closing this in favor of #287.