跟读练习: Pydantic Tutorial • Solving Python's Biggest Problem - 通过YouTube学习英语口语
C2
跟读控制
0% 已完成 (0/119 句)
Welcome to this video tutorial where I'm going to show you how to use the Pydantic module in Python.
⏸ 已暂停
速度:
重复次数:
等待模式:
字幕同步:0ms
所有句子119 句
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.
App Store 和 Google Play 评分 4.9/5
Shadowing English
移动端
随时随地使用 Shadowing English 应用学习英语。今天就提高您的沟通技巧!
跟踪您的学习进度
AI 评分和纠错
丰富的视频库

背景与背景介绍
在这段视频中,讲解者深入探讨了Python编程语言的一个主要问题:动态类型所带来的挑战。Python虽然易于上手,但缺乏静态类型支持,令程序员在开发大型应用时面临变量管理困难。通过使用Pydantic模块,程序员可以在创建数据模型时确保数据的有效性,从而减少潜在的错误。这对于学习英语并理解技术性内容的学习者来说,提供了重要的上下文,帮助他们更好地掌握相关术语和概念。
日常交流的五个常用短语
- “在Python环境中安装Pydantic” - 说明如何开始使用该模块。
- “创建模型实例” - 讲解如何实例化模型以便使用。
- “类型提示让编程更容易” - 强调使用类型提示的重要性。
- “数据验证确保有效性” - 指出数据验证在项目中的重要性。
- “序列化对象到JSON格式” - 描述如何将数据存储为通用格式。
逐步模仿练习指南
为了有效提升您的英语口语能力,可以通过“shadow speak”(影子演讲)进行模仿练习。以下是逐步指南:
- 观看视频并集中注意力:第一次观看时,专注于了解讲解者的内容和表达方式。
- 逐段重放:每段视频播放后暂停,尝试重复讲解者所说的内容。这是实现shadow speech(影子演讲)的方法。
- 注意语音和语调:模仿讲解者的语气和语调,尝试去感受英语的自然流畅感。
- 记录并回放:在练习时录下自己的声音,然后回听,评估你的发音和语流是否清晰。
- 进行日常练习:每天花固定时间进行此练习,以提高你的英语口语能力。通过持续练习,您会发现自己的表达越来越自然。
通过这些步骤,您将能够有效提升您的英语能力,尤其是技术相关的词汇与表达,使得在观看看YouTube学英语的同时,提高自己的语言技能成为可能。
什么是跟读法?
跟读法 (Shadowing) 是一种有科学依据的语言学习技巧,最初开发用于专业口译员的培训,并由多语言者Alexander Arguelles博士普及。这个方法简单而强大:您在听英语母语原声的同时立即大声重复——就像是一个延迟1-2秒紧跟说话者的影子。与被动听力或语法练习不同,跟读法强迫您的大脑和口腔肌肉同时处理并模仿真实的讲话模式。研究表明它能显着提高发音准确性,语调,节奏,连读,听力理解和口语流利度——使其成为雅思口语备考和真实英语交流最有效的方法之一。
