If You’re Not Using Python DATA CLASSES Yet, You Should 🚀

ArjanCodes · Beginner ·🛠️ AI Tools & Apps ·5y ago

Key Takeaways

This video tutorial covers Python's dataclasses, demonstrating how to design and use them for efficient data modeling and manipulation, with tools such as Python, Data Classes, and Pandas.

Full Transcript

data classes in python allow you to write shorter code and initialize print compare and audio data much more easily get yours now for 20 off using the link in the description oh wait this is not a sponsored video and data classes are free i'm going to look at a few practical examples to help you get started right away and become an evil data manipulating overlord let's dive in if you're new here and you want to become a better software developer gain a deeper understanding of programming in general start now by subscribing and hitting the bell so you don't miss anything classes are a combination of two things behavior in the form of methods and data in the form of class attributes they're blueprint for objects they form the basis of object-oriented programming and developers use them in a million different ways some classes are mostly containers of behavior for example a class that allows you to draw all kinds of shapes on the screen or a class that provides password hashing functionality other classes act more as containers of data think of class for representing a vehicle in a vehicle registration system or a class for representing a polygonal mesh in a graphic system when working with behavior container class you might use things like inheritance to change the behavior or use design patterns such as the strategy you probably also won't have that many different instances of that class in your application a class that behaves more like a data container is often used differently you may need to create many instances you want to order them compare them easily inspect the data that's in them etc regular bare bone classes don't really provide a lot of useful functionality for such data-oriented classes that's why some programming languages provide a more data-oriented variant of a class for example c-sharp has a stock type that's much like a class but is more oriented toward representing data structures and since version 3.7 python has a data classes module so how are data classes different from regular classes first data class have a built-in initialize to help you quickly fill an object with data there are easy ways to print compare and order data you can create data that's read-only and they're totally free to show you how data classes work i'm starting with this very simple class person that has a name a job and an age person has nothing more at the moment than an initializer that allows us to create a person with those three values and here i'm creating three persons gerald jennifer and another jennifer you can never have enough jennifer's let's run this code and see what happens so you can see i print the ids of person two and three so that's what you see here and then when i print out person one we get person object at this memory address not very useful information doesn't tell us anything about what's inside the object another thing is that person two and person three are both jennifer they both are sourcers and they're both 25 years old if you compare these two objects the result is false because they are different objects that's when you're dealing with regular classes when you're dealing with data you prefer we want different behavior one thing you'd like is an easy way to print the data instead of having this person object at this address we'd like to see what is the contents of the object another thing is that often with data we want to do deeper comparisons so we know when the data is the same we consider the object also the same which is also not happening here data classes can solve all those things for us so let's turn person into a data class and see what happens so i'm going to import the data class decorator and add it to the person class because now person is a data class we no longer need this initialization method because the data class does this job for us so i'm just going to remove this note that it is important that you provide these type-ins here so dataclass knows what type of data it's dealing with and now i can simply run the same program and you're going to see the behavior is going to be very different let me run this again so now you see we get the ids of the objects they are different but when we compare them the result is actually true because they contain the same data also you note that we're no longer getting this person object at that memory address we're getting a nicely printed representation of the object that contains also the data so we can quickly see what kind of object we're dealing with those are the kind of things that data classes do for you automatically another thing you often want to do with data is comparing data for example like this unfortunately at the moment we cannot compare these objects with because we didn't define what that means with data classes you can define that they can be ordered and we do that by setting the order flag to true and now what happens is this so now you see we can compare these in this case person one is not larger than person two because also we didn't really define what that means if you want to define how to order objects you could add a sort index and that's an int and what we want to do for example suppose you want to sort by age now ideally you want to put somewhere that sword index should contain the age of the person so we can sort by that and the way to do it is in the post init method and the reason we need to do there is because post in it is called after init so the values have been set so we can do something like this the only issue with doing it this way is that sort index is now being used by the data class as a member of the class but we only want to use it for sorting if i try to run this for example you see that we get an error that it's missing a positional argument here because it's expecting a sort index which it's not getting in this constructor so the way to tell data classes that this is a field we're only using for sorting is by using the field function so we're telling data class that sort index is a field but we don't want to initialize it and now let's run this code and see what happens and there we are back again at what we are expecting and you can also see that now person one is deemed larger than person two because we're sorting by h so the result now is true one thing that's not so nice now is that if we print out the data you see that sort index is added here as well and maybe we don't want it there so we can add a extra option here to let the data class know that sort index shouldn't be part of the string representation let's run this one more time and then this is what we get data class also allow you to work with default values let's say we want to add a strength to the character this gives you a default value of strength hundred so if i run this again you'll see that this person here has strength 100 but i can also pass it as a parameter here and now the strength 99 so default values here are very useful so you don't have to initialize them and every time you create a person if we now want to change the sorting index we can very simply do that here by changing the value of h to strength and now we're sorting by strength another nice thing you can do with data classes is that you can freeze them and that's by setting the frozen value there's an issue though if i try to run this you see i'm going to get an error the problem is because it's frozen i cannot assign to the field sort index here obviously the only reason we're doing that here is because we want to be able to sort them but there's a trick that instead of assigning this directly we're calling the set attribute method and that looks like this now i can remove this line and it's going to have the same effect but we're going to circumvent the frozen setting from the data class and now our code works again as we expect and also because we're sorting by strength gerald is no longer larger than jennifer because the object is frozen i'm not allowed to set any attribute to it so if i try to do this we're going to get an error so frozen help you to make sure that data is not changed anywhere in your code so let me remove this because obviously gerald is not 12 years old anymore let's run that again so yeah we're back one final thing i'd like to show you is that there is also a nicer way to print out the data and that's with the underscore underscore string method this is not something that's particular to data classes you can also use it in regular classes but i think it fits nicely into this example so let's say we're going to return here a nice string representation of the person and now when we're printing the person we're going to get our nice string representation so overall data classes allow you to quickly create objects that represent data compare them order them and print them out in an easy way data has become the core of every software application and the amount of data we're consuming is mind-blowing in the beginning of 2020 the amount of data in the world was estimated to be 44 zettabytes which is about 40 times bigger than the number of stars in the observable universe on youtube people watch over a billion hours of video every day imagine all the comments and like data that that generates speaking of which like this video if you are enjoying it in the grand scheme of youtube it's meaningless but you made me very happy in short anything that helps us deal with data more easily is most welcome and data classes surely are a nice addition to python especially because they're free what i haven't really covered yet is software design and architecture aimed at better handling of data there's a lot to talk about ranging from design patterns for ingesting and transforming data to data manipulation patterns used in modules such as pandas data structures and architectures and more i'm surely going to cover those things in the future i hope you enjoyed this if you haven't joined my discord server yet here's the invitation link come over and say hello thanks for watching take care and until the next time [Music]

Original Description

💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide. This video is a tutorial about Python's dataclasses. I take you through an example that shows what you can do with them. Python data classes are - as you'd expect - in particular suitable to model classes that represent data, and as such they offer easy mechanisms to initialize, print, order, sort, and compare data. Note that although I'm using a sort_index attribute, strictly speaking that's not needed in this case, because a data class uses a tuple of its attributes in the class definition as the default for sorting. I'm not a fan of this kind of hidden behavior, so I prefer to do it explicitly (using something that is called sort_index in this case). Another advantage of using a separate field, is that you can do more complicated ordering, using for example a weighted combination of age and strength. 🎓 ArjanCodes Courses: https://www.arjancodes.com/courses. 💬 Join my Discord server: https://discord.arjan.codes. ⌨️ Keyboard I’m using: https://amzn.to/49YM97v. 🔖 Chapters: 0:00 Intro 0:33 Behavior-driven vs data-driven classes 2:11 Explaining the example 3:31 Creating a dataclass 4:37 Sorting and comparing 6:58 Default values 7:40 Creating read-only (frozen) objects 8:55 String representation of data 9:34 Final thoughts #arjancodes #softwaredesign #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from ArjanCodes · ArjanCodes · 16 of 60

1 Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
ArjanCodes
2 FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
ArjanCodes
3 Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
ArjanCodes
4 Build a GLASSMORPHISM React Component - Typescript & Material-UI
Build a GLASSMORPHISM React Component - Typescript & Material-UI
ArjanCodes
5 Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
ArjanCodes
6 100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
ArjanCodes
7 Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
ArjanCodes
8 1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
ArjanCodes
9 Channel Trailer ArjanCodes - March 2021
Channel Trailer ArjanCodes - March 2021
ArjanCodes
10 Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
ArjanCodes
11 Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
ArjanCodes
12 GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
ArjanCodes
13 Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
ArjanCodes
14 Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
ArjanCodes
15 QUESTIONABLE Object Creation Patterns in Python 🤔
QUESTIONABLE Object Creation Patterns in Python 🤔
ArjanCodes
If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
ArjanCodes
17 CODE ROAST: Yahtzee - New Python Code Refactoring Series!
CODE ROAST: Yahtzee - New Python Code Refactoring Series!
ArjanCodes
18 7 UX Design Tips for Developers
7 UX Design Tips for Developers
ArjanCodes
19 Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
ArjanCodes
20 🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
ArjanCodes
21 Do We Still Need Dataclasses? // PYDANTIC Tutorial
Do We Still Need Dataclasses? // PYDANTIC Tutorial
ArjanCodes
22 7 Python Mistakes That Instantly Expose Junior Developers
7 Python Mistakes That Instantly Expose Junior Developers
ArjanCodes
23 Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
ArjanCodes
24 GitHub Copilot 🤖 The Future of Software Development?
GitHub Copilot 🤖 The Future of Software Development?
ArjanCodes
25 More Python Code Smells: Avoid These 7 Smelly Snags
More Python Code Smells: Avoid These 7 Smelly Snags
ArjanCodes
26 Test-Driven Development In Python // The Power of Red-Green-Refactor
Test-Driven Development In Python // The Power of Red-Green-Refactor
ArjanCodes
27 5 Tips To Keep Technical Debt Under Control
5 Tips To Keep Technical Debt Under Control
ArjanCodes
28 Refactoring A Tower Defense Game In Python // CODE ROAST
Refactoring A Tower Defense Game In Python // CODE ROAST
ArjanCodes
29 The Factory Design Pattern is Obsolete in Python
The Factory Design Pattern is Obsolete in Python
ArjanCodes
30 Why the Plugin Architecture Gives You CRAZY Flexibility
Why the Plugin Architecture Gives You CRAZY Flexibility
ArjanCodes
31 Refactoring A Data Science Project Part 1 - Abstraction and Composition
Refactoring A Data Science Project Part 1 - Abstraction and Composition
ArjanCodes
32 Refactoring A Data Science Project Part 2 - The Information Expert
Refactoring A Data Science Project Part 2 - The Information Expert
ArjanCodes
33 Refactoring A Data Science Project Part 3 - Configuration Cleanup
Refactoring A Data Science Project Part 3 - Configuration Cleanup
ArjanCodes
34 Purge These 7 Code Smells From Your Python Code
Purge These 7 Code Smells From Your Python Code
ArjanCodes
35 Running A Software Development YouTube Channel
Running A Software Development YouTube Channel
ArjanCodes
36 Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
ArjanCodes
37 Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
ArjanCodes
38 How To Easily Do Asynchronous Programming With Asyncio In Python
How To Easily Do Asynchronous Programming With Asyncio In Python
ArjanCodes
39 The Software Designer Mindset
The Software Designer Mindset
ArjanCodes
40 NEVER Worry About Data Science Projects Configs Again
NEVER Worry About Data Science Projects Configs Again
ArjanCodes
41 Powerful VSCode Tips And Tricks For Python Development And Design
Powerful VSCode Tips And Tricks For Python Development And Design
ArjanCodes
42 8 Python Coding Tips - From The Google Python Style Guide
8 Python Coding Tips - From The Google Python Style Guide
ArjanCodes
43 What Is Encapsulation And Information Hiding?
What Is Encapsulation And Information Hiding?
ArjanCodes
44 8 Tips For Becoming A Senior Developer
8 Tips For Becoming A Senior Developer
ArjanCodes
45 Building A Custom Context Manager In Python: A Closer Look
Building A Custom Context Manager In Python: A Closer Look
ArjanCodes
46 GraphQL vs REST: What's The Difference And When To Use Which?
GraphQL vs REST: What's The Difference And When To Use Which?
ArjanCodes
47 You Can Do Really Cool Things With Functions In Python
You Can Do Really Cool Things With Functions In Python
ArjanCodes
48 Announcing The Black VS Code Theme (Launching April 1st)
Announcing The Black VS Code Theme (Launching April 1st)
ArjanCodes
49 7 DevOps Best Practices For Launching A SaaS Platform
7 DevOps Best Practices For Launching A SaaS Platform
ArjanCodes
50 Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
ArjanCodes
51 Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
ArjanCodes
52 Things Are Going To Change Around Here
Things Are Going To Change Around Here
ArjanCodes
53 Dependency Injection Explained In One Minute // Python Tips
Dependency Injection Explained In One Minute // Python Tips
ArjanCodes
54 How To Setup A MacBook Pro M1 For Software Development
How To Setup A MacBook Pro M1 For Software Development
ArjanCodes
55 A Simple & Effective Way To Improve Python Class Performance
A Simple & Effective Way To Improve Python Class Performance
ArjanCodes
56 How To Write Unit Tests For Existing Python Code // Part 1 of 2
How To Write Unit Tests For Existing Python Code // Part 1 of 2
ArjanCodes
57 How To Write Unit Tests For Existing Python Code // Part 2 of 2
How To Write Unit Tests For Existing Python Code // Part 2 of 2
ArjanCodes
58 Make Sure You Choose The Right Data Structure // Python Tips
Make Sure You Choose The Right Data Structure // Python Tips
ArjanCodes
59 5 Tips For Object-Oriented Programming Done Well - In Python
5 Tips For Object-Oriented Programming Done Well - In Python
ArjanCodes
60 Next-Level Concurrent Programming In Python With Asyncio
Next-Level Concurrent Programming In Python With Asyncio
ArjanCodes

This video teaches you how to use Python's dataclasses to efficiently model and manipulate data, making it easier to write shorter code and work with data objects. By the end of this tutorial, you'll be able to design and implement dataclasses for your own projects.

Key Takeaways
  1. Create a person class with a name, job, and age
  2. Use the data class decorator to turn the person class into a data class
  3. Remove the __init__ method from the person class
  4. Provide type hints for the data class
  5. Run the same program with data classes
  6. Compare objects with data classes
  7. Define custom comparison and sorting behavior with data classes
  8. Use default values with data classes
  9. Freeze data classes
💡 Data classes in Python provide a convenient way to model and manipulate data, allowing for easy comparison, ordering, and printing of objects, and can be used to create read-only data.

Related Reads

Chapters (9)

Intro
0:33 Behavior-driven vs data-driven classes
2:11 Explaining the example
3:31 Creating a dataclass
4:37 Sorting and comparing
6:58 Default values
7:40 Creating read-only (frozen) objects
8:55 String representation of data
9:34 Final thoughts
Up next
How To Do Complete SEO Audit of a WordPress Website Using Claude AI
Quick Tips - Web Desiign & Ai Tools
Watch →