Pratica di Shadowing: Pydantic Tutorial • Solving Python's Biggest Problem - Impara a parlare inglese con YouTube

C2
Controlli di Shadowing
0% completato (0/119 frasi)
Welcome to this video tutorial where I'm going to show you how to use the Pydantic module in Python.
⏸ In Pausa
Tutte le Frasi119 frasi
1
Welcome to this video tutorial where I'm going to show you how to use the Pydantic module in Python.
2
One of the biggest issues with Python as a programming language is the lack of static typing.
3
Python uses dynamic typing, which means that when you create a variable, you don't have to declare its type, like this x for example.
4
Compare this to something like Java or C where you actually have to declare the type upfront.
5
Once a Python variable is created, you can also override it with a different type than what you created it with.
6
So here if I create x = 10, in the next line I can override that with the word "hello" as a string.
7
And Python allows you to do this. This does make it easier to get started with Python, but it can cause a lot of problems later on.
8
For example, as your app gets bigger, it becomes harder and harder to keep track of all your variables and what type they should be.
9
It's also difficult when you have to work with functions where the argument types aren't obvious.
10
For example, what is this "rect" argument supposed to be here?
11
It could be a tuple, but then it doesn't tell you if the x-axis or the y-axis should come first.
12
But the biggest downside of using dynamic types by far is that it allows you to accidentally create an invalid object.
13
By that, I mean an object with values that it shouldn't be allowed to have.
14
For example, here I'm trying to create a person and the second argument is supposed to be age, so it's supposed to be a number.
15
In the first example, I created correctly with 24 as an integer, but in the second example, I created with 24 as a string.
16
And both of them might work at the beginning. Python will allow you to do this and things can actually seem fine for a while.
17
But eventually, when you do try to use that age variable as a number, it will fail.
18
This can be really hard to debug because the failure could occur at any time in your program.
19
And it could be hard to associate that failure with the actual cause.
20
Luckily, these days, Python has a lot of tools you can use to solve these problems.
21
This includes dataclasses and type-hinting, like in this code example here.
22
But today, we're going to be taking a look at Pydantic.
23
It's an external library and it gives you powerful tools to model your data and solve all of these problems that we've just been talking about.
24
Pydantic is a data validation library in Python.
25
It's used by some of the top Python modules out there, notably HuggingFace, FastAPI, and LangChain.
26
Its main benefits are that by modeling your data, you get better IDE support for type-hints and autocomplete.
27
You can also validate your data so that when you create an object, you can be 100% sure that it's valid and it won't fail you later.
28
And finally, if you ever need your data to be in a universal format like JSON, Pydantic gives you an easy way to serialize your objects.
29
This really comes in handy if you need your Python app to talk to other apps on the internet, or if you just want to save your data to disk.
30
Let's take a look at how all of that works.
31
First, make sure that you've installed Pydantic into your Python environment. You can do it using this command.
32
To create a Pydantic model, first define a class that inherits from the base model class.
33
Inside the class, define the fields of the model as class variables.
34
In this example, I'm creating a user model and it's got three fields, a name, which is a string, an email, also a string, and an account ID, which is going to be an integer.
35
You can create an instance of the model like this and then just pass in the data as keyword arguments.
36
You can also do this by unpacking a dictionary.
37
So this works well if you already have the data and you just want to put it inside the model.
38
For example, you have a response from an external API.
39
If the data that you've passed in is valid, then this user object will be successfully created.
40
You can then access each of the attributes of the user object like this.
41
I'm going to head over to my IDE so I can show you how this works in action.
42
I have my user model defined here and I think by far the most useful feature of modeling your data is that you get type hints in your IDE.
43
So what I mean is if I start typing out my user, I get autocomplete and auto suggestions based on this model.
44
So here I've created this user object and I haven't filled in the data yet, but if I mouse over it, it actually tells me which arguments it accepts.
45
And here I can fill it in with the examples you saw earlier, so a valid name, a valid email, and an account ID.
46
And now if I print the user, you can see that all of this information is contained in this one object.
47
And of course the type hinting makes it easier to work with when you actually need to use one of these models.
48
So for example here, if I'm printing the user, I can just press a dot and then I get a list of all the valid variables associated with it.
49
So for example, if I wanted email, I just start typing and it knows that this user has an email attribute.
50
With type hints, your code becomes much easier to work with because you don't have to remember everything yourself.
51
Your IDE does it for you, and this is especially useful if you're working with really large code bases or if you need to collaborate with other developers.
52
Pydantic also provides data validation right out of the box.
53
This means that if you try to create an object with the wrong type of data, it will fail right then and there.
54
This is good because if your software has to fail, then it's better that it fails as early as possible.
55
This will make it easier to debug.
56
So let's go back to our example here and see how that works.
57
If I try to create this user with an account ID that's not an integer, for example if I turn it into a string and I try to run it, I now get a validation error.
58
So I can see immediately that I tried to create this object with the wrong type of data.
59
And in cases like these, I much rather it fail right away with the descriptive error message than silently succeed, but then fail at some point much later down the line.
60
You can also validate more complex types of data.
61
For example, let's say I wanted to validate that this string is actually a valid email.
62
First, let's change it to an invalid email, for example just Jack on its own.
63
So this is no longer an email, and if I run this it still works because all this checks for is that it's a string.
64
But I can actually import a special data type called email string from Pydantic.
65
And if I replace this instead and run this again, you'll now see that I get this validation error and that this string here is not a valid email.
66
So let me change this back to a valid email again and see if that works.
67
And after fixing this value, the validation passes.
68
So I have an easy way to assert that this email field always has a valid email string.
69
If none of the inbuilt validation types cover your needs, you can also add custom validation logic to your model.
70
For example, let's say that we want to enforce that all account IDs must be a positive number.
71
So we don't accept negative integers for our account ID.
72
This is what we can add to our class to make that happen.
73
First, we'll have to use this validator decorator from Pydantic.
74
And then we write a custom function.
75
This is going to be a class function.
76
And then inside the function, we can check if the value is less than or equal to zero.
77
And if it is, we can raise a value error saying that this is not a valid value for this field.
78
But if it is, we can return the value.
79
So let's go back to our code editor and try that out.
80
And here I've imported this validator decorator.
81
And this is the validation logic I'm adding as a class function of this user model.
82
And here you can change this validation condition to whatever you want it to be for your app.
83
But in this case, I'm just checking that it's greater than zero.
84
So if I run this with my current data, it should still work.
85
And here you can see that it's fine.
86
But if I change this to a negative number, let's see what happens.
87
Now it fails with that validation error and it says the account ID must be positive.
88
And here we can actually make the error message really descriptive because we can print anything we want here. And we can even print the value that the user tried to create this model with.
89
Another great thing about Pydantic is that it provides built-in support for JSON serialization.
90
Makes it really easy to convert Pydantic models to or from JSON.
91
To convert a Pydantic model to JSON, you can call the JSON method on the model instance.
92
This will return a JSON string representation of the model's data.
93
So if you print it out, you'll see something like this.
94
And if you don't want a JSON string, but you just want a plain Python dictionary object instead, you can use this dict method.
95
If you have a JSON string that you want to convert back into a Pydantic model, you can use the parse_raw method.
96
And since JSON is widely used and understood across every major tech stack, this feature will make it really easy to integrate your Python code with external applications or APIs.
97
Finally, let's see how Pydantic compares to dataclasses, which is Python's built-in module that solves a similar problem.
98
As great as Pydantic sounds, Python actually does ship with some data modeling and type hinting capabilities on its own.
99
For example, you can already specify type hints like this, and most IDEs should pick it up.
100
There's also an inbuilt module called "dataclass" in Python that lets you create a class with fields.
101
So if you haven't used it before, this is what the syntax looks like.
102
It's very similar to Pydantic, except instead of extending from a base model class, you're using this "@dataclass" decorator instead.
103
As you can see, it's also really easy to use.
104
So how does this compare to Pydantic? Well, let's take a look at some of the top criteria.
105
They actually both give you type hints in the IDE, which personally is the biggest reason for using these libraries to me.
106
So both of them tick that box.
107
Dataclasses, however, does not give you any easy validation or deep JSON serialization out of the box.
108
Now, if validation is a big deal for you, for example, you have a lot of emails or you have a lot of fields where the data type is very specific, then you probably should go with Pydantic.
109
If you're using dataclass, then your JSON serialization capability isn't as good out of the box as Pydantic.
110
But if your data is simple enough, you can still do some basic serialization with a one-liner like this.
111
The one major advantage that dataclasses have over Pydantic is that they're in-built into Python directly.
112
That means that it's more lightweight and you don't even have to install it.
113
For many users, this may be enough.
114
If you want some rough guidance as to which module you should use, then I recommend Pydantic if you have complex data models or you need to do a lot of JSON serialization or you need to work with a lot of external APIs.
115
But if data validation isn't important to you and your data isn't super complex, you can get away with dataclasses.
116
And that's it for Pydantic.
117
If you haven't used it yet, then give it a try and let me know what you think.
118
If you've enjoyed this video and want to see more tutorials like this, then please subscribe to the channel and let me know in the comments what type of topics or modules you'd like to see covered next.
119
Otherwise, I hope you found this useful and thank you for watching.
4.9/5 su App Store & Google Play

Shadowing English Su Mobile

Impara l'inglese sempre e ovunque con l'app Shadowing English. Migliora le tue capacità di comunicazione oggi stesso!

Tieni traccia dei tuoi progressi di apprendimento
Valutazione e correzione degli errori tramite intelligenza artificiale
Ricca libreria video
Shadowing English Mobile App

Informazioni su Questa Lezione

In questa lezione, imparerai a utilizzare il modulo Pydantic in Python, affrontando uno dei problemi più significativi del linguaggio: la mancanza di tipizzazione statica. Con il dinamismo di Python, potresti trovarti a gestire variabili di tipi diversi, il che può causare confusione e difficoltà nel rilevamento degli errori. Attraverso questo tutorial, esplorerai come Pydantic può aiutarti a modellare i tuoi dati, validare le informazioni e garantire che gli oggetti creati siano sempre validi, migliorando così l'affidabilità del tuo codice.

Vocabolario e Frasi Chiave

  • Pydantic: Una libreria per la validazione dei dati in Python.
  • Tipizzazione Dinamica: Sistema che permette di non dichiarare il tipo di una variabile al momento della creazione.
  • Validazione dei Dati: Processo per garantire che i dati siano conformi a un determinato formato o criterio.
  • Oggetto: Un'istanza di una classe che contiene attributi e metodi.
  • Type Hinting: Suggerimenti di tipo che aiutano a identificare il tipo di una variabile o di un argomento.
  • Serialization: Processo di conversione di un oggetto in un formato che può essere facilmente salvato o trasferito, come JSON.
  • Autocompletamento: Funzione degli IDE che suggerisce automaticamente le parole o i metodi mentre si digita.

Consigli per la Pratica

Per migliorare la tua pronuncia inglese e le tue abilità di conversazione, ti incoraggio a utilizzare tecniche di shadowing mentre segui questo video. Shadow speak è particolarmente efficace quando il parlato è chiaro e diretto, come nel tutorial di Pydantic. Fai attenzione al ritmo del narratore che parla con una buona articolazione, ti consigliamo di ripetere esattamente ciò che senti, cercando di imitare non solo le parole, ma anche l’intonazione e il tono. Questo ti aiuterà a familiarizzare con i termini tecnici in inglese e a migliorare la tua pratica di conversazione in inglese.

Inoltre, considera l’utilizzo di un shadowing site che offre video risorse simili a questa, dove puoi esercitarti nel tuo tempo libero. Riascoltare sezioni specifiche del video e ripeterle ad alta voce ti aiuterà a consolidare ciò che hai appreso. Ricorda che la chiave del successo nel shadowing è la costanza; quindi, non esitare a inserire queste pratiche nella tua routine di studio quotidiana.

Cos'è la tecnica dello Shadowing?

Shadowing è una tecnica di apprendimento delle lingue supportata da studi scientifici, originariamente sviluppata per la formazione dei traduttori professionisti e resa popolare dal poliglotta Dr. Alexander Arguelles. Il metodo è semplice ma potente: ascolti un audio in inglese di madrelingua e lo ripeti immediatamente ad alta voce — come un'ombra che segue il parlante con un ritardo di solo 1–2 secondi. A differenza dell'ascolto passivo o degli esercizi di grammatica, lo shadowing costringe il tuo cervello e i muscoli della bocca a elaborare e riprodurre simultaneamente i modelli di discorso reale. La ricerca dimostra che migliora significativamente la precisione della pronuncia, l'intonazione, il ritmo, il discorso connesso, la comprensione dell'ascolto e la fluidità del parlato — rendendolo uno dei metodi più efficaci per la preparazione alla prova di speaking dell'IELTS e per la comunicazione reale in inglese.

Offrici un caffè