2

In my current project, we are using an OpenAPI-to-TypeScript-API generator, that generates automatically typed functions for calling API endpoints via Axios. In Python, we use snake_case for our class properties, while in TypeScript we use camelCase.

Using this setup, we have found that the alias property (Field(..., alias="***")) is very helpful, combined with the allow_population_by_field_name = True property.

Simple model class example:

from pydantic import BaseModel, Field

class MyClass(BaseModel):
    my_property: str = Field(..., alias="myProperty")

    class Config:
        allow_population_by_field_name = True


if __name__ == "__main__":
    my_object = MyClass(my_property="banana")

The question is: Why doesn't Pylance understand that I want to be able to write MyClass(my_property="banana")? See screenshot from vscode below:

Screenshot of error in VSCode

Is there any way to configure Pylance/Pydantic/vscode to better understand this?

"Just living with" this is problematic because having red lines like this in our code promotes a mindset of "red is probably ok", so they lose their power.


Edit May 8th, 2023:

We found a way to "circumvent" this problem, by creating a wrapper class, containing an alias_generator. It doesn't seem like pylance picks up on this, and therefore it acts as if it doesn't exist.

I'm sure using the system like this isn't something people do a lot, but this helped our team. Also it allows us to not write = Field(..., alias="camelCase") everywhere.

Sebastian
  • 1,321
  • 9
  • 21

1 Answers1

3

It seems like this is a known problem as you can see from issue #4936. It has to do with the way dataclass_transform (from PEP 681) handles the alias field attribute.

There is currently no elegant solution for this, but there may be with Pydantic v2 at some point.

I agree that you should not just passively ignore the warnings. It is always better to explicitly ignore them, if you did everything you could to fix the underlying issue.

Therefore I propose this is a clear-cut use case for # type: ignore or more specifically # pyright: ignore as suggested here in the documentation.

Sometimes you just hit the limits of the Python typing system. And when you do, explicit ignore-directives are the correct way to deal with that.

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41