Pydantic field does not take value

Viewed 14

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.

a.dict()
{'name': 'joe'}

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

Many thanks

1 Answers

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_

Related