The video effectively demonstrates how dependency injection bridges the gap between simple scripting and professional software architecture in Python. It is a concise masterclass on achieving true modularity and testability without over-complicating the codebase.
Deep Dive
Voraussetzung
- Keine Daten verfügbar.
Nächste Schritte
- Keine Daten verfügbar.
Deep Dive
Dependency Injection in Python is AwesomeHinzugefügt:
How's it going everyone? In today's video, we're going to learn about dependency injection. One of those programming concepts that sounds fancy and complicated, but is actually really practical once you see it in action. The reason I like dependency injection so much is that it makes your code so much more flexible and testable. Instead of hard- coding dependencies inside your functions or classes, you pass them in from the outside. This might sound like a small change, but it has huge implications for how you write and maintain code. To show you what I mean, let's look at a practical example. We'll build a user data class that can serialize itself to different formats.
I'll show you the hard-coded approach first, then I'll show you how we can refractor it to use dependency injection. But before we continue, I'd just like to thank Zed for sponsoring this video. Zed is a lightning fast code editor written in Rust and I've been using it to do all my coding for months now. If you feel like trying out Zed, I've left a link in the description box down below where you can download it for free. Anyway, let's get back to the video. So, for the first example, we will create some data we want to deserialize and we will do that inside the user data class. This will be based off of a common pattern I've seen where people match a type of serializer.
What's important to note inside this user data class is that we have a method called serialize and this will serialize to a string. The format is hard-coded as a string parameter. Every time we add a new format, we need to modify this method. And scrolling down, we also have a des serialized method which also takes a format. And once again, this is hard-coded. And to show you what this class does, we're just going to create our main entry point, create a user instance, and create some JSON output using the serialized method we have in the class. Then we're going to print the user instance and what was serialized to JSON. And finally, just to show you that we can, we're going to serialize the user to toml format. Now when we run this what we should get as an output is the user serialized to JSON and the user serialized to TOML. So both of those work as expected and we can also des serialize back from serialized data. To do that we just need some JSON data and using this we can use the class method des serialize and once again we can pick the format we want to use. Now when we run this we should get the des serialized data back as an output. If we wanted to add a new type of serialization such as YAML or Webpack, we would have to alter both the methods on the user class. This breaks something called the open and closed principle.
The idea is that objects should be extendable without needing to modify them. These classes go against this principle by forcing us to update the class every time there is a change in specification or functionality. As applications grow, this can become an increasing source of bugs and technical debt. Next, let's fix these problems using dependency injection and the strategy pattern. Instead of passing a string like JSON or toml, we pass in a strategy object to the serialize/d serialize methods. This way, the user class doesn't need to know about specific formats. So, let me show you how this works in practice. And to do so, we need to go all the way back to the top and create a protocol. But before we do that, we're going to import YAML. And from typing, we're going to import any and protocol. And above the data class, we're going to create a class called serializer strategy, which is a protocol. And this protocol uses structural subtyping which means any object with these methods works. No need to inherit or implement anything explicitly. So the first method we want inside here is the serialize method. And this will take some data of type dictionary of string to any. Then below that we need another method called des serialize which takes data of type string and converts it into a dictionary of type string to any. Next we create a class for each strategy which will allow us to pass them as an object to the objects serialization methods. This will prevent us from hard- coding them and using if else chains to decide which one to use. So the first one I want to create is the JSON serializer and this will contain the JSON serialization strategy. Then we will create one for the toml and we will create one for the YAML. As you can see each one of these serializers handles serializing and deserializing in their own way. Then we can go to the user data class and inside the serialize method we will change the format to a strategy which will be of type serializer strategy and instead of all of this we will return the strategy.
serialize as a dictionary. So instead of passing a string to match against we can pass the strategy directly. And we're going to want to do the same thing for des serialize. So scrolling down we will change the format to a strategy and then we can remove all of this des serialize the data and return that data. Now our class adheres to the open and closed principle. We can define as many strategies as we like and we will never have to change a line of code in our user class. This means our class is now open for extension but closed to modification. Hence the name open and closed. So next we can go to our main entry point and test it out. And first we should create a user and below the user we can try out the three serializers starting with the JSON serializer then the TOML serializer and finally the YAML serializer. So now when we run this we should get back the three versions of the user. The first one which uses the JSON strategy, the second one which uses the toml strategy and the third one which uses the YAML strategy.
And we can also do it the other way around. So if we have some JSON data, we can des serialize it using the JSON serializer class. So here we will grab the user using the des serialize method and then we will print that we des serialized it from JSON using the strategy and to prove that we're going to print the username the user email the user age and the user roles and when we run this we should get Bob bob atample.com 25 and user and finally I'm going to show you another way to do dependency injection without defining classes here what we're going to do is simply define tupils of encoder/deoder pairs then pass them around. This is useful when you don't want to define a full class for a simple strategy. Let me show you how this works. So for this example, we're going to import the partial function from funk tools. Then inside the data class, we're going to have to fix the serialized method and the des serialized method. In this case, instead of using a serializer strategy, we're going to say that the strategy is of type tupil. Then we're going to extract the encoder from the strategy and we're going to return that encoder.
Then for the des serialized method, we're going to do the same thing except this time we're going to extract the decoder, grab the data from it, and return the class with the data. And pyrite isn't really happy about this type because it's a bit far too generic.
But that's fine for now because what I want to show you is how simple a strategy can be. Here we're going to make use of funk tools to define default parameters and reference them when needed. These will perform the exact same functionality as our classes did before, but with none of the overhead.
Depending on your project goals, these could be contained in a registry or an enum 2. So for the JSON strategy, we're going to create a partial which uses JSON dumps with an indentation of two.
And the second item of this tupil will be JSON loads. The second strategy will use TOML dumps and TOML loads. And the YAML strategy will use a partial which includes YAML.dump and YAML.safe.
Quite often in tutorials explaining design patterns and principles, they show the pattern in a very strictly defined fashion. But in the wild, these patterns can take a number of different forms, each with the same idea at its core with very different implementations and styles. Now, let's go back to the main entry point and use these strategies. So as always we will start off by creating an instance of a user and then we will use our strategies and instead of instantiating the object we just have to pass in a tupil. So here we're passing in the JSON strategy tupil then the TOML strategy tupil and finally the YAML strategy tupil. And when we run this we will get each one of these objects serialized using their respective strategy. The first one used the JSON strategy. The second one used the toml strategy and the third one used the YAML strategy and once again we can also des serialize data. So for this example we're using the deserialize method on the JSON data using the JSON strategy and once we do that we will get back the username, the email, the age and the roles. But yeah, that just about covers everything I wanted to talk about in today's video. Do let me know in the comment section down below whether you have any other questions regarding dependency injection. But otherwise, with all that being said, as always, thanks for watching and I'll see you in the next
Ähnliche Videos
Agentforce NOW AMA: Build with React and Salesforce Multi-Framework
SalesforceDevs
490 views•2026-05-28
How agent o11y differs from traditional o11y — Phil Hetzel, Braintrust
aiDotEngineer
450 views•2026-05-28
WEB TECHNOLOGIES UNIT-2 | Degree 4th sem BCOM Computers web technologies unit-2 full explanation💯✅
LearnwithSahera
1K views•2026-05-29
More tests are always better? How to use AI to identify tests that bring little value
Alliance4Qualification
335 views•2026-05-29
Search Algorithms Explained in 60 Seconds! 🤖💨
samarthtuliofficial
218 views•2026-06-01
People of Game of Thrones using JavaScript DOM
AltCampus
296 views•2026-05-30
Introduction to Problem Solving Part - 1 | Lecture 1 | Intermediate DSA
ascensionix
107 views•2026-05-29
So What's Odin Lang Even Good For
TechOverTea
131 views•2026-06-01











