1
from pydantic import BaseModel

class Test(BaseModel):
    val1 = str
    val2 = str

test = {
    "val1": "1010101",
    "val2": "1010101",
}
test_value= Test(**test)

print(test_value) # this doesn't display anything
print(test_value.val1) # this only display `<class 'str'>`

I have this simple structure of using pydantic. But when I try to print the value, it doesn't display anything.

Am I missing something here?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
kaiser
  • 115
  • 10

1 Answers1

1

You have to use : between the field name and its type instead of =.

class Test(BaseModel):
    val1: str
    val2: str
Hernán Alarcón
  • 3,494
  • 14
  • 16
  • 1
    Adding some explanation: `val1 = str` _assigns_ a value to the model's field, while `val1: str` _annotates_ the field that it should be a string. See related [What are variable annotations?](https://stackoverflow.com/q/39971929/2745495). Pydantic's model definitions takes advantage of _annotations_. – Gino Mempin Apr 25 '22 at 08:42