What are __slots__ in Python? Optimize Your Code!

NeuralNine · Beginner ·💻 AI-Assisted Coding ·2y ago

Key Takeaways

The video explains the use of __slots__ in Python for code optimization, covering the basics of slots and their application in improving code efficiency.

Full Transcript

what is going on guys welcome back in this video today we're going to learn about slots in Python and how we can use them to reduce memory usage into to speed up our code so let us get right into [Music] ited all right so we're going to learn how to optimize our python code using slots and Slots is basically an attribute that we can Define in classes to explicitly state which attributes we expect our instances to have and this leads to faster exess time into to less memory usage uh for this we're going to go right into an example now one thing that we need to install first is a package that I introduced in the last video which is memory profiler just so we can track how much memory is actually being used for this you can use pip or pip 3 to install memory unor profiler this is just a package that allows us to track how much memory is being used in specific functions so what we're going to do now first is we're going to use one example we're going to code one example without using slots we're going to measure the memory usage and the time and then we're going to do the same thing with slots to see what changes so we're going to start here by importing statistics so that we can have multiple runs that we can take the mean from so that we have a more representative number um and then we're going to also say from memory profiler import memory usage and we're also going to import time it so time it and statistics are core python packages this is the one that we installed and now now I'm going to just Define a simple class called Point without slots and this class of course will not use slots we're just going to use basic python we're going to Define in a nit method we're going to have the parameters X and Y here in the Constructor and we're going to say self.x equals x self.y equal y um and that is basically now our class so by default we don't have a slots attribute so we just have have these attributes implicitly defined here so we say there is self.x self.y and so on and then we can go ahead and say p equals 1020 for example actually Point without slots print p.x p.y and you can see I get the values here now what this already creates in the background is an attribute called uncore uncore dict uncore uncore and this dictionary basically contains the variable names or the attribute names and the respective values this is what you get without using slots now to see what memory usage and performance we have here or speed we have here we're going to define a function create uh points and this function will basically just return uh a list comprehension so a list based on a list comprehension we're going to say points without slots and I I for I in range and we're just going to Define find uh a long range here let me just see what did I use here I used 1 million so I'm going to use 1 million here again uh and this is what we're going to track now so we create 1 million instances of these points here and we're going to do that 10 times so we're going to say m values equals an empty list time values equals an empty list and then we're going to say four placeholder in range 10 times what I want to do is I want to say the M usage without points uh is going to be equal to memory usage this is now from memory profiler uh and this function here we're going to pass the create points function uh which is going to be passed without calling it so we're passing it as an entity like this without the parenthesis uh and we're going to define the interval to be 0.01 and then basically we're going to say m values append and I only want to append the max value so max meem usage without points um I think we can also do that here with uh Max usage equals true but let's do it like this now uh just to be safe so we append this memory usage of this particular run to M values and now we're going to uh do the same thing with time so time without slots is going to be equal to time it time it and then Lambda um Point actually let's create a point here I'm going to say point is equal to point without slots one two and we're going to say point x point Y this is now the excess time so we're not actually tracking the time for the creation here we're using the or we're tracking the memory usage for the creation but we're tracking the excess time here so how how long does it take to access X and Y here uh and we want to do that a million times as well like this um and then we say again time values append time without slots and in the end what we want to print here is we want to print the mean so statistics mean of M values statistics mean of time values that is basically it so now let's run this let's see if I messed up anything or if we're going to get a number here and we should get the average um the average memory usage here so 235 and here we get 0.06 seconds it's quite fast uh but yeah this is the result now of this um benchmarking you could say now let's go ahead and copy this and create a second file let's call this Main 2py and here now we're going to do it with slot so we're going to say point with slots and what we're going to do here is we're going to define the following attribute the following class attribute uncore uncore slots uncore uncore equals and now basically here we pass a list or we Define a list of all the fields that we're going to use x and and you can already see here I defined X and Slots now the error message is gone here but I don't have Y which is why it says here points with slots object attribute Y is read only so I have to actually put it here to be able to set y to something so this is how it works now what you will see here and I'm going to comment this out for a second is when I go ahead and I say p equals point with slots 1020 and I try to print P doore uncore dictionary uncore uncore you can see that it doesn't have this attribute so basically using slots uh forbids this dictionary to be created this is how it basically say saves uh the access time and the the memory usage because it forbids or it denies dictionary and also weak references here uh to be to be used when we store values we Define them explicitly here the attributes in the slots class attribute so what we can do now is we can basically uncomment all this we can change this to with slots and we can change this to with slots everything else should stay the same and then we should be able to see a difference here so I'm going to run this and we should hopefully see that we're using less memory and the access time will probably be roughly the same so you can see first of all maybe I can run this here uh can I not run this at the same time how do I do that in py charm I'm not sure but you saw we had something like 120 something and here we had 230 something so the access time is let's just copy this values here these values here um like this and let's run this to compare the values here I think the access time is not that different in this case but the memory usage is definitely different you can see here it's a little bit faster but this could also just be some random fluctuation but this one here is definitely lower than this one so we use way less memory for the same functionality we don't lose any functionality the only thing is of course now we cannot dynamically just introduce new variables or new attributes uh if they're not defined in slots so that is of course a downside we can maybe increase the number here to 10 million to see if this changes something I mean of course it's going to change the run time but uh maybe we can see more of a difference here so maybe it now takes half a second to do that there you go so this is the value that we have for 10 million here and now let's run this with 10 million and maybe we're going to see some larger difference now here so this was the first value with slots and now hopefully we see something that's slower but we could also see something that's faster I'm not sure if that makes so much difference here there are of course scenarios in which this makes a lot of difference yeah you can see it actually takes some some longer if I increase this now to 100 million and to um 1 billion you would see even more so all these uh small differences here actually would or these here all these small differences here would actually make more of a difference as we go to larger and larger numbers but yeah this is how you can optimize your python code and your python classes using slots so that's it for today's video I hope you enjoyed it and hope you'll learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you in the next video and bye

Original Description

In this video, we learn about slots in Python and how we can use them to optimize our code. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 💼 Services 💼 💻 Freelancing & Tutoring: https://www.neuralnine.com/services 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎙 Discord: https://discord.gg/JU4xr8U3dm
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to use __slots__ in Python to optimize code, explaining the benefits and application of slots in improving code efficiency. By watching this video, viewers can learn how to write more efficient Python code. The video is beginner-friendly and provides a clear introduction to the concept of slots.

Key Takeaways
  1. Define a class with __slots__
  2. Understand the benefits of using __slots__
  3. Apply __slots__ to optimize code
  4. Test the optimized code
  5. Refactor existing code to use __slots__
💡 Using __slots__ can significantly improve code efficiency by reducing memory usage and improving performance.

Related Reads

Up next
Copilot Cowork: Setup, Skills, Plugins & Pricing
Matt Tutorials
Watch →