1

Why doesn't this work for my case?

# Windows 10
# Python 3.11.8
# Pydantic 2.7.3
# Mypy 1.10.0
"""mypy.ini
[mypy]
plugins = pydantic.mypy
"""
# https://stackoverflow.com/questions/69433904/assigning-pydantic-fields-not-by-alias
from pydantic import BaseModel, Field, ConfigDict


class Params(BaseModel):
    var_name: int = Field(alias='var_alias')

    model_config = ConfigDict(
        populate_by_name=True,
    )

Params(var_alias=5)  # no works
Params(var_name=5)   # works
"""
mypy .\tess.py
tess.py:20: error: Missing named argument "var_name" for "Params"  [call-arg]
Found 1 error in 1 file (checked 1 source file)
"""

My code is identical to Assigning Pydantic Fields not by alias but I get an error, I don't understand why
Expected:

mypy .\tess.py
Success: no issues found in 1 source file
1
  • Why doesn't it work for me? And gitlab-ci is also for me @toyotaSupra Commented Jun 6, 2024 at 11:33

1 Answer 1

1

Seems like you need to add a default value to work:

[mypy]
plugins = pydantic.mypy
from pydantic import BaseModel, Field, ConfigDict


class Params(BaseModel):
    var_name: int = Field(42, alias='var_alias')

    model_config = ConfigDict(
        populate_by_name=True,
    )

Params(var_alias=5)  # now works too
Params(var_name=5)   # works
Success: no issues found in 1 source file
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible without the default value?
I couldn't find anything without

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.