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

Dot syntax not working correctly for pydantic 2 models #604

Open
findmyway opened this issue Oct 25, 2024 · 1 comment
Open

Dot syntax not working correctly for pydantic 2 models #604

findmyway opened this issue Oct 25, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@findmyway
Copy link

🐛 Bug report

To reproduce

from jsonargparse import CLI
from pydantic import BaseModel, Field
from typing import Annotated, Literal, Union


class PingTask(BaseModel):
    type: Literal["ping"] = "ping"


class PongTask(BaseModel):
    type: Literal["pong"] = "pong"

Task = Annotated[
    Union[PingTask, PongTask],
    Field(discriminator="type"),
]

def train_func(model: Task) -> None:
    print(model)


if __name__ == '__main__':
    CLI(train_func, as_positional=False)

It works well when the model argument is specified as a json string:

$ python x.py --model '{"type": "ping"}'
type='ping'

However, it doesn't work using the dot syntax:

$ python x.py --model.type ping                                                                                                

usage: x.py [-h] [--config CONFIG] [--print_config[=flags]] --model MODEL
error: Parser key "model":
  1 validation error for tagged-union[PingTask,PongTask]
    Unable to extract tag using discriminator 'type' [type=union_tag_not_found, input_value=NestedArg(key='type', val='ping'), input_type=NestedArg]
      For further information visit https://errors.pydantic.dev/2.9/v/union_tag_not_found. Got value: NestedArg(key='type', val='ping')

Expected behavior

Environment

  • jsonargparse version: 4.33.2
  • Python version: 3.11.9
  • How jsonargparse was installed: pip install jsonargparse
  • OS: mac
@findmyway findmyway added the bug Something isn't working label Oct 25, 2024
@mauvilsa
Copy link
Member

Thank you for reporting! I took a quick look. Seems that this happens with pydantic 2 but works fine with pydantic 1. Not sure why. Will look in more detail later.

@mauvilsa mauvilsa changed the title [Question] How to use the dot syntax correctly? Dot syntax not working correctly for pydantic 2 models Oct 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants