If you're not using Python DATA CLASSES yet, you should ๐Ÿš€



If you're not using Python DATA CLASSES yet, you should ๐Ÿš€

If you're not using Python DATA CLASSES yet, you should ๐Ÿš€

๐Ÿ’กHere’s my FREE 7-step guide to help you consistently design great software: https://arjancodes.com/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.

๐Ÿš€If you want to take a quantum leap in your software development career, check out my course The Software Design Mindset: https://www.arjancodes.com/mindset.

๐Ÿ›’ GEAR & RECOMMENDED BOOKS: https://kit.co/arjancodes.

Some interesting links:
– https://realpython.com/python-data-classes/
– Frozen instances: https://docs.python.org/3/library/dataclasses.html#frozen-instances
– If you want to go ‘next-level’ with dataclasses, check out Pydantic (https://pydantic-docs.helpmanual.io/). Pydantic enforces type hints at runtime, and offers a really nice extension for data validation.
– The code from this video is available here: https://github.com/ArjanCodes/2021-dataclasses

๐ŸŽ“ Sign up to Brilliant now and get 20% off the annual subscription: https://brilliant.sjv.io/arjancodes.

๐Ÿ’ฌ Join my Discord server here: https://discord.arjan.codes
๐ŸฆTwitter: https://twitter.com/arjancodes
๐ŸŒLinkedIn: https://www.linkedin.com/company/arjancodes
๐Ÿ•ตFacebook: https://www.facebook.com/arjancodes

๐Ÿ”– 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

Thumbnail photo background by Markus Spiske: https://unsplash.com/@markusspiske

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!

Comments are closed.