Pydantic Flashcards

(4 cards)

1
Q

What is Pydantic?

A

Pydantic is the most widely used data validation library for Python. It is used to typecheck variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Describe a basic example of Pydantic use for a User class

A
  • from pydantic import BaseModel, PositiveInt, ValidationError
  • class User(BaseModel):
    . key: datatype
    . id: int
    . age: PositiveInt
  • data = {id: 4, age: 28}
  • exampleUser = User(**exampleUser)

exampleUser.id // gives the id
exampleUser.model_dump() // gives the whole item

If you use it on different data that does not meet requirements, it will result in a ValidationError
try:
. User(**unsuitable_data)
except ValidationError as e:
. print(e.errors())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are some common Pydantic imports?

A

BaseModel, ValidationError, PositiveInt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are some parts of Pydantic people don’t know about?

A

One of the great things about Pydantic is, if it can, it will convert your data to the appropriate type (eg dates formatted correctly, or number to string conversion).

It works with Rust under the hood, making it super fast.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly