Eric
Eric

Reputation: 31

How do I resolve an AttributeError when I return a class-level attribute from within a class method in a Pydantic model?

I cant seem to wrap my head around this AttributeError. I defined a Pydantic model using BaseModel, set my default attribute with type annotation, created my method using @classmethod and within this function, I want to return a class-level attribute.

Code:

from pydantic import BaseModel

class  ExtractionModel(BaseModel):
    llm_model: str = 'gpt-4'


    @classmethod
    def create_llm(cls):
        return (cls.llm_model)


print(ExtractionModel.create_llm())

Error:

Traceback (most recent call last):
  File "/Users/erics-mac/Desktop/project-app/server/src/extract_text/v1/config-test.py", line 13, in <module>
    print(ExtractionModel.create_llm())
  File "/Users/erics-mac/Desktop/project-app/server/src/extract_text/v1/config-test.py", line 10, in create_llm
    return (cls.llm_model)
  File "/Users/erics-mac/Desktop/project-app/env/lib/python3.9/site-packages/pydantic/_internal/_model_construction.py", line 210, in __getattr__
    raise AttributeError(item)
AttributeError: llm_model

Any insight is much appreciated!

I get the returned value from invoking the attribute name on the instance model, so I know that the default value is set.

Upvotes: 2

Views: 1389

Answers (2)

user2357112
user2357112

Reputation: 281476

If this thing is supposed to be a class attribute, you should annotate it as one:

from typing import ClassVar
from pydantic import BaseModel

class ExtractionModel(BaseModel):
    llm_model: ClassVar[str] = 'gpt-4'

    @classmethod
    def create_llm(cls):
        return (cls.llm_model)

Right now, you're annotating it as an instance attribute, so Pydantic removes the 'gpt-4' value from your class's attributes while processing your class.

Upvotes: 3

Lucas Moura Gomes
Lucas Moura Gomes

Reputation: 182

What you want to do is probably remove @classmethod. That decorator is used to create a method accessible without instantiating an object of the class i.e ExtractionModel.create_llm(), and you're only using it after instantiating it.

from pydantic import BaseModel

class ExtractionModel(BaseModel):
  llm_model: str = "gpt-4"

  def create_llm(self):
     return (self.llm_model)

extraction_model = ExtractionModel()

print(extraction_model.create_llm())

Upvotes: 1

Related Questions