Pydantic field does not take value


While attempting to name a Pydantic field schema, I received the following error:

NameError: Field name "schema" shadows a BaseModel attribute; use a different field name with "alias='schema'".

Following the documentation, I attempted to use an alias to avoid the clash. See code below:

from pydantic import StrictStr, Field
from pydantic.main import BaseModel    

class CreateStreamPayload(BaseModel):
          name: StrictStr
          _schema: dict[str: str] = Field(alias='schema')

Upon trying to instantiate CreateStreamPayload in the following way:

a = CreateStreamPayload(name= "joe",
            _schema= {"name": "a name"})

The resulting instance has only a value for name, nothing else.

{'name': 'joe'}

This makes absolutely no sense to me, can someone please explain what is happening?

Many thanks

Asked By: Eric31



From the documentation:

Class variables which begin with an underscore and attributes annotated with typing.ClassVar will be automatically excluded from the model.

In general, append an underscore to avoid conflicts as leading underscores are seen as either dunder (magic) members or private members: _schemaschema_

Answered By: Maximilian Burszley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.