Тёмный

A Simple & Effective Way To Improve Python Class Performance 

ArjanCodes
Подписаться 236 тыс.
Просмотров 99 тыс.
50% 1

There's a very simple way to improve Python performance of your code. And you know what's so nice about this performance improvement? It also nudges you to use good Python software design practices - it's a win-win!
The code I worked on in this episode is available here: github.com/ArjanCodes/2022-slots.
💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
💻 ArjanCodes Blog: www.arjancodes.com/blog
🎓 Courses:
The Software Designer Mindset: www.arjancodes.com/mindset
The Software Designer Mindset Team Packages: www.arjancodes.com/sas
The Software Architect Mindset: Pre-register now! www.arjancodes.com/architect
Next Level Python: Become a Python Expert: www.arjancodes.com/next-level...
The 30-Day Design Challenge: www.arjancodes.com/30ddc
🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes.
🎓 Sign up to Brilliant now and get 20% off the annual subscription: brilliant.sjv.io/arjancodes.
👍 If you enjoyed this content, give this video a like. If you want to watch more of my upcoming videos, consider subscribing to my channel!
💬 Discord: discord.arjan.codes
🐦Twitter: / arjancodes
🌍LinkedIn: / arjancodes
🕵Facebook: / arjancodes
👀 Code reviewers:
- Yoriz
- Ryan Laursen
- Sybren A. Stüvel
- Dale Hagglund
🎥 Video edited by Mark Bacskai: / bacskaimark
🔖 Chapters:
0:00 Intro
0:50 How classes work in Python
2:00 Descriptors
2:46 Basic class example with the dict dunder method
3:53 Using slots
5:02 Slots performance test
6:07 Using slots with dataclasses
7:19 Slots performance test #2 (with dataclasses)
8:00 Why are slots not used by default?
8:39 Slots limitation: mixins and multiple inheritance
10:23 Slots limitation: dynamic attributes
11:25 Final thoughts
#arjancodes #softwaredesign #python
DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!

Опубликовано:

 

31 май 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 205   
@ArjanCodes
@ArjanCodes 7 месяцев назад
💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
@cychoboy
@cychoboy 2 года назад
Slots can also help you avoid certain types of bugs. For instance person.addres = "abc" becomes an error because "address" was misspelled. Vanilla classes will accept this input without any error leaving you to figure out why the address field wasn't changed as intended.
@foji-video
@foji-video 2 года назад
that I think is actually the main advantage when building serious applications
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 года назад
If you have read/write properties on a class, specifying slots is a very good idea.
@SkyOceanNet
@SkyOceanNet Год назад
I actually had that error inside my code for such a long time undiscovered. Recently I found it while reforming the code. Now I'm using slots and it can prevent that kind of mistakes. Thanks to Arjan and Edmunds!
@artyomvancyan2000
@artyomvancyan2000 2 года назад
It is nice to see new videos about python but it's coming unactual more as there are a bunch of video curses about python. I very like your videos about project architecture and the unique code examples that you were using. I would really like to see in your channel videos about UML diagrams, project file structure, documenting packages and modules, design patterns that you haven't talked about them yet, etc. Thanks for your job.
@PeterSeres
@PeterSeres 2 года назад
I second the opinion that the most interesting videos are that teach us how to reduce coupling in the code by using design patterns and how to make python projects that are scalable.
@hanabimock5193
@hanabimock5193 2 года назад
Totally agree on that. Also if performance is a problem, just avoid python.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks & no worries - there will definitely be more of those videos in the future.
@jacksonarnold27
@jacksonarnold27 Год назад
Yes!! Project structure, program flow design, design patterns, etc would be great!! Same with UML stuff, I’d love some in depth videos on any of these
@Sam-qn6hl
@Sam-qn6hl 2 года назад
Amazed that nobody has questioned using the lower bound rather than an average metric, or plotting the distribution of the different runs. It's not clear that a lower minimum translates into general better performance in most cases, especially a "20%" difference. Having said that, this was an interesting video. Might run some of those tests myself.
@isaacwolf2806
@isaacwolf2806 2 года назад
Same thing I was thinking! Typically I like to see min, mean, and max. And if I'm trying to convince a coworker my way is better then I just take the best one. 😁
@fjolublar
@fjolublar 2 года назад
the lower minimum is the most accurate measurement to take
@rafarios50
@rafarios50 2 года назад
@@fjolublar why is it the most accurate?
@henrikholland1730
@henrikholland1730 2 года назад
Great video as always. Love the new studio set up.
@willemvdk4886
@willemvdk4886 2 года назад
Congrats on the new studio/office, Arjan! Looking good. Good to see the contents don't suffer the even better look. Still very informative! Love it. Kappertje gepakt trouwens?
@Mr1995Musicman
@Mr1995Musicman 2 года назад
This is a great feature. Dynamic members is like loose typing: it sounds great as a beginner developer, but as a more experienced developer it's more often a headache
@arpitkumar4525
@arpitkumar4525 Месяц назад
Even as a experienced dev, dynamic attributes and pretty much non existent boilerplate code seriously helps in prototyping or testing out risky features(risky in terms of feasibility). But other than that of course these should be avoided like the plague
@_.gray._
@_.gray._ 2 года назад
Loving the new setup! This explains slots really well, and I might just remember to use them next time I write a class haha.
@chaddrobertson5805
@chaddrobertson5805 2 года назад
I was recently told about slots on an SO question that I'd answered, and was quite confused by the concept until now. This was a fantastic explanation - thank you! A big +1 for touching on inheritance (was my largest concern as I was watching).
@EngHassanIbraheem1998
@EngHassanIbraheem1998 2 года назад
You have a fantastic skill in choosing topics. Keep it up.
@fuadpalchayev7269
@fuadpalchayev7269 2 года назад
Thank you! Very informative👍
@Vdherrlichkeit
@Vdherrlichkeit 2 года назад
Again. Great content Arjan. Highly appreciated
@CornishMiner
@CornishMiner 2 года назад
I'm liking the new setup Arjan. Super clear video and great sound.
@steshinanton
@steshinanton 2 года назад
The videos are amazing! I like the way you explain things. It is easy and fun to follow. I always find something useful even if I know the topic and recommend your videos to my colleagues because they are so informative. The way you present inspires me when I do my presentations. The new setup is very nice!
@sami3592
@sami3592 2 года назад
Nice video. I also like your new setup. Your explanation of the topic always best. Thanks man.
@zacharyAbresch
@zacharyAbresch 2 года назад
Looking stellar mate, sharp looks to match yer words!
@casperschutte2516
@casperschutte2516 2 года назад
Thanks for the videos. They are always super interesting and very practical
@anhnguyenuc6543
@anhnguyenuc6543 2 года назад
Thanks for your video. That's really what I needed
@obsidiansiriusblackheart
@obsidiansiriusblackheart 2 года назад
This is such a fantastic video and the fact that it's completely free is astounding!
@Swissfonk
@Swissfonk 2 года назад
Love your new Studio.
@flightmansam
@flightmansam 2 года назад
Fantastic video. I’m gonna use slots for sure! Also yes, I love the new look. Enjoy your week!
@MaksimKupfer
@MaksimKupfer 2 года назад
Really insightful my friend, and great pace as well! Looking forward to following your content.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Maxim, glad you liked the content!
@ajflorido
@ajflorido 2 года назад
Cool video, a very good explanation indeed. And a really cool recording setup :D
@wowzers94
@wowzers94 2 года назад
I dig the new set! And thanks as always for the python tips!
@TechieGuy82
@TechieGuy82 Год назад
Superb as always. Thumbs up
@sasha297603ha
@sasha297603ha 2 года назад
Great new studio and very interesting topic. Well done
@nsontung
@nsontung Год назад
Thank you so much, Arjan, great lesson. It improved my code performance a lot.
@ArjanCodes
@ArjanCodes Год назад
Glad you liked it!
@heljhumenad
@heljhumenad 2 года назад
This is so much informative especially on perf of py classes
@q2kq885
@q2kq885 2 года назад
Dataclass is truly a powerful structure in python. I'm really looking forward to learning more tips and tricks to make the python code faster. This tutorial is helpful. Thanks a lot!
@mahmudulhassan9043
@mahmudulhassan9043 2 года назад
Thank you very much . i love all of your tutorial . it helps me lot to improve my skill .
@jakob1379
@jakob1379 2 года назад
Nice video! A great way to better show the value of variables is with 'from rich import print'. It automatically highlights types and emphasizes structure.
@davidlinesq
@davidlinesq 2 года назад
Love the new recording setup! Thanks for the content and hope you get to 100k subscribers soon.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks David!
@dhruvakashyap
@dhruvakashyap 2 года назад
Amazing new setup! Great video as always!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you!
@PedigreeGuitars
@PedigreeGuitars 2 года назад
Great video. Always learning with you. The new setup look great!!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Pedro!
@jonathanheadley2729
@jonathanheadley2729 2 года назад
the setups are really nice! excellent work.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Jonathan!
@jpconstantineau
@jpconstantineau 2 года назад
Great video! I wonder if micropython and circuitpython support slots at all. Python on microcontrollers can use all the performance help and this is something most people wouldn't even know about.
@malteplath
@malteplath 2 года назад
I can see that you are proud of your new studio/office - and you should be! One aspect of inheritance with slots that you didn't mention, and that I am unsure about: how do you add new attributes in a class that inherits from a class with slots? Do you have to declare __slots__ again in the subclass?
@pthube
@pthube 2 года назад
Thanks for sharing this cool feature
@cryptosimon9529
@cryptosimon9529 2 года назад
great setup!
@Michael201078
@Michael201078 Год назад
Slots - very useful think. Thank you for the explanation.
@ivolol
@ivolol 2 года назад
I think you could add a translucent rectangle code graphic inset under the shelf light or something, on the left at 1:00 that could help show the code structure of the very things you're talking about, would work really well
@MagnusAnand
@MagnusAnand 2 года назад
Fantastic video!
@alilee4505
@alilee4505 2 года назад
Hey Arjan, congrats to your new setup! Looking forward to achieving 100k subs 👍
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Ali!
@PawelOlas
@PawelOlas 2 года назад
the new backgrounds and cameras you use are very nice. pro!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks Pawel!
@holographicsol2747
@holographicsol2747 Год назад
thank you that just helped a lot as i remembered watching this a while ago and came back to refresh my mem!
@ArjanCodes
@ArjanCodes Год назад
Glad to hear you found it helpful!
@holographicsol2747
@holographicsol2747 Год назад
@@ArjanCodes awesome
@valenciawalker6498
@valenciawalker6498 Год назад
Thank you
@dqalombardi
@dqalombardi 2 года назад
I felt so certain that this was just going to be clickbait but honestly it just makes so much sense and I can't believe I didn't know about this before now.
@lungenbrotchen
@lungenbrotchen 2 года назад
Thank you for your videos. I learned a lot from them and I also like the entertainment factor of your videos.
@ArjanCodes
@ArjanCodes 2 года назад
Thank you so much - glad to hear the videos are helpful to you!
@BartKevelham
@BartKevelham 2 года назад
Awesome new setup Arjan! If I'm very nitpicky (but that's not a thing I would ever be) then I'd say the programming view could use a bit of fill light for the right side of the face. But quite an awesome step up already. And besides that, another excellent video. Keep it up!
@ArjanCodes
@ArjanCodes 2 года назад
Thanks Bart! I agree & it’s already fixed for the next batch 😊.
@saeedgnu
@saeedgnu 6 месяцев назад
In Go, you can "compose" several structs in a bigger struct, and get convinience of multiple inheritance, without inheritance at all. But in Python, sometimes the only way to make your class smaller is to use multiple inheritance. I think in some ways, Go is a better Python than Python (based on the Zen of Python).
@python_byte
@python_byte 2 года назад
Awesome, amazing way to create a well readable and secure code
@jakesurrett3518
@jakesurrett3518 2 года назад
Sweet new set! Just a little feedback: I would love to see a little bit of graphics/illustrations/diagrams sprinkled in the explain-to-camera sections. When there is a visual complement to the topic/explanation at hand I just can't help but feel more engaged in the discussion. Fireship on RU-vid has mastered this technique in place of appearing on camera at all (which I'm certainly not suggesting). SciShow is another excellent example of this technique in action. I suppose news broadcasts had this figured out from the start. Anyhow, food for thought at least and thanks for another great python video.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks for the suggestion Jake, I agree that would be helpful!
@dedekind1982
@dedekind1982 2 года назад
Thanks! Find ways to keep delivering value like this. Thank you
@ArjanCodes
@ArjanCodes 2 года назад
Thank you, will do!
@unusedTV
@unusedTV 2 года назад
Audio has a bit more echo than in the past, in the first two setups. Coding setup is fine.
@theherk
@theherk 2 года назад
Dang, That set looks superb.
@demasjaring5435
@demasjaring5435 2 года назад
Awesome camera quality 👌
@ArjanCodes
@ArjanCodes 2 года назад
Thank you!
@niksen3300
@niksen3300 2 года назад
Hey Arjan! I have been watching your videos and i have a question that i could not find a clear answer to. Is there a reason to NOT use dataclasses? It really seems to be the cleaner approach to managing and writing your classes but are there reasons to pick normal classes over them? Great content by the way! Loving your channel.
@kenhaley4
@kenhaley4 2 года назад
Very nice...as usual. It seems like another advantage of using slots would be to catch spelling errors in your classes' attribute names. For example, without slots, the statement myPerson.namee = "Joe" would work fine, but myPerson.name would not be affected. But using slots, the statement would raise an error: 'Person' object has no attribute 'namee' which would let you find and fix the spelling error much sooner.
@ZeZa1515
@ZeZa1515 2 года назад
Really liking the new setups! Your face in the coding setup had a lot of shadows on it though, so it wasn't very clear
@vlntsolo
@vlntsolo Год назад
Thanks!
@ArjanCodes
@ArjanCodes Год назад
Thank you Valentyn, glad you liked it!
@gshan994
@gshan994 2 года назад
I like dat you are trying to be like other youtubers wid d lights in BG n all. But i subscribed your channel solely for the knowledge u share. Yes, the setup is good, but honestly I loved your setup with a straight up facing camera.
@ardaakdere
@ardaakdere 2 года назад
Really cool and energetic also!
@Hubert4515
@Hubert4515 2 года назад
we love the new setup! :D
@ArjanCodes
@ArjanCodes 2 года назад
Thanks!
@christianforster3408
@christianforster3408 2 года назад
Hi Arjan, love your videos! Just one little note. Wouldn't it be a better measure to use the average performance, than the minimal one? At least I'd be more interested in the average difference in performance ;) Cheers!
@jonathan3488
@jonathan3488 2 года назад
Hi, great video. Does this work the same for private and protected attributes?
@bryangalindo
@bryangalindo 2 года назад
Nice setups!! The changing light in the first setup was a little distracting, but the other setups were perfect. Also, thanks for sharing how slots work, its limitations, and providing a real-life example of a tool using slots. Very informative!
@enigq
@enigq 2 года назад
May I just say that I love the graph monster in the background?
@Rebeljah
@Rebeljah 2 года назад
I like the new set!
@jusce17
@jusce17 2 года назад
Performance wise, if we use data type when declaring variable (e.g a:int = 10), does it anyhow improve the performance ?
@rajat971
@rajat971 2 года назад
@arjan - Should we always user dataclasses even if we have a lot of business centric complex methods in the Class or should be only use dataclass for saving data in class and using simple get set methods?
@jimboppin2461
@jimboppin2461 2 года назад
great vids, just heads up new sound is a little boxy/tinny 👍
@PracticalPillow
@PracticalPillow 2 года назад
Honestly, this is the first time I see slots, but I have a question. Does performance grow for get, set and delete evenly or some of them has a bigger contribution? Thanks you for the video!
@SarcTiann
@SarcTiann 9 месяцев назад
excellent explanation
@ArjanCodes
@ArjanCodes 9 месяцев назад
Glad it was helpful!
@newoptionz
@newoptionz Год назад
Thanks @ArjanCodes. Unfortunately I have not yet seen your free 7-step guide? I have signed up at the link you indicate and even purchased some of your courses by I haven't found this elusive guide, lol. Please help.
@jimmyf.x.9526
@jimmyf.x.9526 Год назад
So amazing I want to use the f word! Fantastic!!!
@MrDowntemp0
@MrDowntemp0 Год назад
Is it possible to use descriptors for validating attributes in a class that uses slots?
@KurtCostaPeters
@KurtCostaPeters 2 года назад
Hello, i tryed to downlod the guide on description, but it didnt accept my mail addres.. it says that the value is invalid
@kalagecko77
@kalagecko77 9 месяцев назад
Thank you Arjan! I using classes in a raspberry pi 4 to perform face tracking with 2 servo motors. Since I am using python 3.9 with no slots attributes for dataclasses, I am using the classical class definition with slots. Unfortunately I couldn't see any improvements. Without using classes or functions I've got an incredible FPS rate. I've tried to switch to python 3.10 using pyenv and venv. Unfortunately I am facing some dependency problems with a library (libcam) that is installed with apt-get install instead of pip3. So I cannot run the program with python3. 10 to test performance. Maybe you have a good hint here for solving this dependency issue. Thx
@Burbinox
@Burbinox 7 месяцев назад
What about the case when we will have a list object as a slot? Does that make sens?
@pedroazambuja132
@pedroazambuja132 2 года назад
Damn looking good man 🕴
@gshan994
@gshan994 2 года назад
I mostly use python for aws cdk. And for architectural diagrams i use plant uml diagrams.
@ThomasConrad
@ThomasConrad 2 года назад
Very informative. I honestly didn't know this. Free performance increases are the best performance increases.
@spell105
@spell105 6 месяцев назад
There is no such thing as a free lunch, it's worth knowing about the limitations of slots.
@MarcelSchliesser
@MarcelSchliesser 2 года назад
Danke!
@ArjanCodes
@ArjanCodes 2 года назад
Thank you, Marcel!
@djangodeveloper07
@djangodeveloper07 2 года назад
high quality content about python on this Channel. No Doubt in it
@ArjanCodes
@ArjanCodes 2 года назад
Thank you Ahmad, glad you like it!
@gheefop
@gheefop 2 года назад
no hoodie? Arjan I think this strapping professional has taken over your channel 🤣 new sets look great
@SuperGrimmy
@SuperGrimmy 7 месяцев назад
After python 3.11 the benefits of using slots on performance is very low as far as I can see, but you are still saving memory. That's not a bad thing for object you create a lot of instances of.
@castares
@castares 2 года назад
Good video, thank you for your content. But, shouldn’t you use mean instead of min when calculating performances? Those mins could be outliers
@derekreed6798
@derekreed6798 5 месяцев назад
So __slots__ = __dict__ could be used in most cases for improved performance (except multi inheritance)?
@ac130kz
@ac130kz 2 года назад
I think attrs is such an awesome thing, it is faster than dataclasses, has validation, extra features, and the slots are enabled by default!
@nocodenoblunder6672
@nocodenoblunder6672 2 года назад
What is attrs?
@burnere633
@burnere633 2 года назад
h4X0r Arjan to corporate Arjan. Also changing lights in the background is a bit distracting.
@callumfleming8662
@callumfleming8662 2 года назад
Like number: 660 great video, didn't even know slots existed! thank you!
@Rodrigo-rq1dx
@Rodrigo-rq1dx 2 года назад
The sofa set (0:54) has a lot of potential for you to add animations to explain what you're talking about. Like sketches/code snippets that illustrate.
@ArjanCodes
@ArjanCodes 2 года назад
Good suggestion! I definitely want to explore animations to improve the clarity of the videos.
@robertbrummayer4908
@robertbrummayer4908 2 года назад
Hi Arjan, great video! I also like your new setup. However, as also other commented, the audio seems to be worse than before.
@ArjanCodes
@ArjanCodes 2 года назад
Thanks! The audio could indeed be better, still have to tweak the new setup a bit, but we’ll get there.
@janHodle
@janHodle 2 года назад
Thank you! Your content belongs to the better ones here on RU-vid!
@ch4sethe5un
@ch4sethe5un Год назад
How does slots works with __post_init__?
@johncongerton7046
@johncongerton7046 7 месяцев назад
The best tutor of all
@ArjanCodes
@ArjanCodes 7 месяцев назад
Thank you for the kind words, John!
@TehCannonMan
@TehCannonMan 2 года назад
Wasn't able to replicate this example using python 3.10.4, for some reason TypeError: dataclass() got an unexpected keyword argument 'slots' and TypeError: unsupported operand type(s) for |: 'type' and 'type' ~ from the get_set_delete function
@StevenMartinGuitar
@StevenMartinGuitar 2 года назад
The shirt seems a little formal :D but the new recording setup looks dope!
@ArjanCodes
@ArjanCodes 2 года назад
Haha, yeah I thought let’s change things a bit for fun. Next time, back to hoodies & simple shirts 😁
@shamaldesilva9533
@shamaldesilva9533 2 года назад
Damnnnn that background 🤩👏👏👏
@ArjanCodes
@ArjanCodes 2 года назад
Glad you like it!
@marcioneto3016
@marcioneto3016 2 года назад
The new setup is looking great! Great video, as usual.
Далее
Все мы немного Адриана 😂😂😂
00:11
The Ultimate Guide to Writing Functions
24:31
Просмотров 176 тыс.
The Flaws of Inheritance
10:01
Просмотров 883 тыс.
The Ultimate Guide to Writing Classes in Python
25:39
Просмотров 104 тыс.
This Is Why Python Data Classes Are Awesome
22:19
Просмотров 788 тыс.
5 Good Python Habits
17:35
Просмотров 337 тыс.
Protocol Or ABC In Python - When to Use Which One?
23:45
PLEASE Use These 5 Python Decorators
20:12
Просмотров 89 тыс.
5 Useful Python Decorators (ft. Carberra)
14:34
Просмотров 83 тыс.