Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydantic object has no attribute '__fields_set__' error

I'm working with FastAPI to create a really simple dummy API. For it I was playing around with enums to define the require body for a post request and simulating a DB call from the API method to a dummy method.

To have the proper body request on my endpoint, Im using Pydantic's BaseModel on the class definition but for some reason I get this error

File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__setattr__ 
AttributeError: 'MagicItem' object has no attribute '__fields_set__'

I'm not sure what's the problem, here is my code that generate all this:

enter image description here

enter image description here

enter image description here

I'm kinda lost right now cuz I don't see the error in such a simple code.

like image 467
BrunoX Avatar asked Jan 21 '26 08:01

BrunoX


1 Answers

You basically completely discarded the Pydantic BaseModel.__init__ method on your MagicItem. Generally speaking, if you absolutely have to override the Base Model's init-method (and in your case, you don't), you should at least call it inside your own like this:

super().__init__(...)

Pydantic does a whole lot of magic in the init-method. One of those things being the setting of the __fields_set__ attribute. That is why you are getting that error.

I suggest just completely removing your custom __init__ method.

One of the main benefits of using Pydantic models is that you don't have to worry about writing boilerplate like this. Check out their documentation, it is really good in my opinion.

PS:

If you insist because you want to be able to initialize your MagicItem with positional arguments, you could just do this:

class MagicItem(BaseModel):
    name: str
    damage: Damage

    def __init__(self, name: str, damage: Damage) -> None:
        super().__init__(name=name, damage=damage)
like image 54
Daniil Fajnberg Avatar answered Jan 23 '26 23:01

Daniil Fajnberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!