0

Problem:

I'm using Pydantic to structure my code, and Pyre (aka pyre-check) to type check. In the following sample, the code works and mypy doesn't complain but Pyre gives error:

Uninitialized attribute [13]: Attribute first is declared in class Name to have type str but is never initialized.

Code:

from __future__ import annotations
from pydantic import BaseModel

class Name(BaseModel):
    first: str

n = Name(first="test")

print(n)

Is Pyre incompatible with Pydantic, or is this user error on my part?

I understand Pyre wants to see the attribute initialized (for example first: str = "Bob") but setting such an equality would indicate to Pydantic that the field is optional (it's not).

Other solutions I've considered and discarded:

  • Pyre doesn't complain if I make Name a dataclass (but then I lose Pydantic features)
  • Adding Field to each attribute eg first: str = Field(..., alias="first_name") - this seems hacky and labor intensive (there are many such BaseModel classes in my code)

Thanks for your help!

FlightPlan
  • 43
  • 1
  • 8
  • For Pydantic, `Optional[str]` means that the attribute is of type `Union[str, None]`. On the other hand, I don't know `Pyre` but it seems it needs you to initialize attributes so I think you can safley use `first: str= ""`. – chc Jul 19 '23 at 08:44
  • Thanks, @chc. In this case, `Optional[str]` isn't the solution because the type should be a non-optional string. In Pydantic, `first: str='""` gives the attribute a default value which solves Pyre's concern, but creates a new problem in that it indicates to Pydantic that the attribute should be optional (it's not). – FlightPlan Jul 19 '23 at 08:52
  • 1
    From [the docs](https://pyre-check.org/docs/errors/#13-uninitialized-attribute), "Pyre currently knows that that uninitialized attributes of classes wrapped in dataclass and attrs decorators will generate constructors that set the attributes. But it does not understand many custom libraries that do similar things" and "There is not currently a way to fix this other than via pyre-ignore or pyre-fixme directives". – FiddleStix Jul 19 '23 at 13:18
  • 1
    Thanks, @FiddleStix! I appreciate the link, and this does seem to get to the root of the problem. For those reading this post in the future: I landed on [this related issue](https://github.com/facebook/pyre-check/issues/504) in the Pyre GH repo, which may be illuminating. – FlightPlan Jul 24 '23 at 02:47

0 Answers0