This Is Why Python Data Classes Are Awesome

Поделиться
HTML-код
  • Опубликовано: 6 фев 2025

Комментарии • 522

  • @ArjanCodes
    @ArjanCodes  Год назад +7

    💡 Get the FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.

  • @sbeau
    @sbeau 2 года назад +181

    Arjan, your ability to explain detail in a structured, easy to follow format is second to none. Thank you for another great tutorial.

  • @saketh_s
    @saketh_s Год назад +40

    One thing to note, when you pass data class "frozen=True", instance is immutable.
    So at 13:29 you are actually getting error for search_string which we are trying to change at _post_int_ at object creating not for person name (line 25)
    You can not change fields even inside the class even with setter methods.

  • @vedambala
    @vedambala Год назад +20

    Arjan,
    You should seriously consider doing a full fledged Python course from beginner to advance level laden with Projects so we can learn Python the Pythonic way.

  • @jordansilke3629
    @jordansilke3629 2 года назад +13

    This is truly an excellent successor to your earlier video on data classes, bravo!

    • @ArjanCodes
      @ArjanCodes  2 года назад +2

      Thanks Jordan, glad you liked it!

  • @hematogen50g
    @hematogen50g Год назад +11

    I came to Python from C# so I picked up coding quickly. But thinking in python way is harder, so such videos really help me develop python mindset.

  • @_sonicfive
    @_sonicfive 9 месяцев назад

    00:02 Data classes are aimed at helping write data-oriented classes.
    02:14 Defining a str method to customize class printing
    04:21 Python data classes make it easy to define classes with instance variables.
    06:27 Data classes provide a solution for default values to avoid sharing references.
    08:42 Customizing data class initialization and instance variable behavior
    10:54 Python data classes provide options to control access and visibility of class attributes
    12:58 Python data classes can be made read-only using the 'frozen' argument
    14:59 Python 3.10 data classes improvements
    17:05 Python data classes use slots for faster instance variable access.
    18:57 Python 3.10 introduces performance improvements using union syntax and slots.
    20:55 Python's freedom comes with performance trade-offs.

  • @coupmd
    @coupmd 2 года назад +81

    Enjoyed this video. Would enjoy more videos on intermediate/advanced python standard library tools and their examples of their intended use cases.

  • @Cloudvenus666
    @Cloudvenus666 2 года назад

    Thanks!

  • @bryan_hiebert
    @bryan_hiebert Год назад +2

    Just like every video from you my knowledge of programming with python is advanced. I really appreciate the content you provide, thank you!

  • @Volcan-kf3oz
    @Volcan-kf3oz Год назад +15

    This guy really know what he is doing every video I've seen he able to break it down to where even a person new to python can understand
    "if you can't explain it simply, you don't understand it well enough." - Albert Einstein

  • @mpotane
    @mpotane 2 года назад

    Wow, the most complete tutorial I've seen. Not a single detail has been missed.

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks, glad you liked it!

  • @techassets
    @techassets 2 года назад +16

    I have an observation. Even if you remove the person.name = "Arjan" and set the dataclass frozen=True you will have a FrozenInstanceError. Because you use the __post_init__ method and the frozen dataclass does NOT allow it ! So you must remove the __post_init__ method if you want to freeze the dataclass and prove that you cannot modify it after initialization.
    THANK YOU FOR YOUR AMAZING VIDEOS !

    • @MiguelRozsas
      @MiguelRozsas 2 года назад

      so, you are saying we not have both ? A frozen class and __post_init__ ? There is any workaround for this ?

  • @neoporcupine
    @neoporcupine 2 года назад +2

    Working my way through my third LinkedIn Learning (LIL) Python course, all of which claim to teach you the data structures available. Arjan's short video explains a dozen reasons why you want to use dataclass that the LIL courses didn't include. Thank you!

  • @equu497
    @equu497 2 года назад

    I wasn't even trying to learn about dataclasses...but it came up on my recommended and I watched the entire thing- Got me thinking I should clean up some old code.

  • @mampiisaotaku
    @mampiisaotaku 2 года назад

    i just discovered your channel a few videos back. and what you share is pure gold

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thank you so much, glad you like it!

  • @alfonsov3190
    @alfonsov3190 2 года назад

    I had a couple of questions during the video, but immediately after they surged, you addressed them. Thanks a lot, as usual!

  • @AbhishekVaid
    @AbhishekVaid 10 месяцев назад

    The progression of introducing features and clarity of explanation is very high ! Great Job !

    • @ArjanCodes
      @ArjanCodes  10 месяцев назад

      Glad you liked the video!

  • @Cookie-mv2hg
    @Cookie-mv2hg 2 года назад +27

    Since we're talking a lot about dataclasses, I wonder would it be great combining with sql database. If we could get a review that would be very helpful!

  • @sambeard4428
    @sambeard4428 Год назад

    Geweldig en duidelijk overzicht van deze erg handige feature. Gisteren liep ik precies nog tegen deze use case aan, veel boillerplate code. Dit lost het mooi op. Thanks!

  • @naderbazyari2
    @naderbazyari2 Год назад

    I am modifying my code in pycharm right now according to your tips. Awesome video. Much much appreciated.

  • @paulorsbrito
    @paulorsbrito 10 месяцев назад +25

    What happened to “explicit is better than implicit” and to “there should be only one obvious way to do something”?

    • @beershigachi4797
      @beershigachi4797 6 месяцев назад +6

      Zen of Python. I love that. So when I saw dataclasses I decided to use Haskell as my primary language.

    • @SkyyySi
      @SkyyySi 21 день назад

      "explicit is better than implicit" is mainly refering to strong vs weak typing. Python doesn't do nonsense like automatically parsing a string into a number.
      As for "there should only be one obvious way to do something", the emphasis is on "obvious". There's an unlimited number of ways to represent record-like data in Python, but none are quite like a dataclass.

  • @ritzg98
    @ritzg98 Год назад +11

    This guy is excellent. I've only watched a couple of his videos so far. Planning on watching a few more today.
    Clear, concise, accessible. So far, great!

  • @FrankenLab
    @FrankenLab 2 года назад +1

    @ArjanCodes, great video. I consider myself a casual programmer and have been programming with Python for about 5yrs and absolutely love it. I started programming "casually" in the 80's with C, Pascal, Assembler, then Perl and now Python. I really enjoyed C and Perl, but Python is by far my favorite now. This is the first video I've seen of yours and based on that I just subscribed to your channel. I enjoy your style and explanations and I don't have to play the video at twice the speed waiting for you to get to the point. I'm looking forward to seeing more of your Python videos.

  • @wtfKwaku
    @wtfKwaku 2 года назад

    OMG, I been working on this project and for like 3 days I been trying assign a class and return something! Great Video!

  • @WalterBoring
    @WalterBoring 2 года назад

    Cool video. I didn't even know about the dataclasses lib until this. I'm putting it into my project now.

  • @songsft.googleassistant2542
    @songsft.googleassistant2542 2 года назад +3

    May you have tons of subs Arjan cause you're one of the few youtubers whose python codes aren't messed up and you're instructions are on the point and useful.

  • @Rebeljah
    @Rebeljah 2 года назад +3

    New AC video! I am actually using DCs right now to define a common set of data for server/client communication. It's very nice because I can subclass a super dataclass in order to get functionality like serialization/deserialization fairly easily. Adding new data types just takes a few lines of code now!

    • @centar1595
      @centar1595 2 года назад +4

      So you're enjoying the AC/DC video? :)

    • @Rebeljah
      @Rebeljah 2 года назад

      @@centar1595 yes I am! Lol

  • @amadzarak7746
    @amadzarak7746 Год назад

    Wow! How did I JUST find this channel. You are awesome man!

  • @amosmunezero9958
    @amosmunezero9958 2 года назад

    Great tutorial in Python, its been a while I havent done some Python, I didnt know much about DataClass. So thank you.

  • @ChrisPatti
    @ChrisPatti 2 года назад

    I really love this video! It’s an excellent quick, guided tours to how powerful data classes, can be. Thanks for making it!

    • @ArjanCodes
      @ArjanCodes  2 года назад +1

      Thank you Christopher. Glad it was helpful!

  • @Rebeljah
    @Rebeljah 2 года назад +1

    I am 100% gonna use the repr=False option, thank you!

  • @ninadloke785
    @ninadloke785 2 года назад

    Watching your video for first time. Deserves subscribe!! Great work and thanks!!

  • @barrykruyssen
    @barrykruyssen 2 года назад

    Hi Arjan. Great video, very well presented. I've just found your channel and will be watching all your videos as time permits. I'm a retired software engineer (started back in the early 80's). 5 weeks ago I decided, in my retirement, to switch back to linux (and python - which I have never used), just for fun, after 25 years in microsoft products (prior to that I was in the Unix world).
    I'll be changing 2 of my classes to data classes ASAP.
    I have just read your Software Design Guide and agree with much of what you've written. I think you have glossed over the most important aspect "Who’s it intended for?". Determining who is doing what, why they do it and what they expect from it and then managing the expectations is the key to a successful implementation. You do mention your “zoom out and zoom in” approach which probably encompasses this but in my planning, the people are the key and if there are problems in this area it can be very costly down the track (we qualified our prospective clients and if the people problem was too great we walked away from deals), as you say we write the code for the client, not for us.
    Thanks

  • @giannimariani9744
    @giannimariani9744 6 дней назад

    At 13:27 you hinted that it was the name change that failed the frozen=True test, however it was the _search_string initialization in __post_init__ that failed.
    If you used datatrees, you can use the self_default field option:
    @datatree(frozen=True)
    class Person:
    ...
    _search_string: str = dtfield(self_default=lambda self: f"{self.name} {self.addr}")
    It gets around the need to create a post_init for this case.

  • @zuydra
    @zuydra 2 года назад +1

    Hi Arjan, your videos on Python are the best I have ever seen on RUclips. Please keep up the good work 👍

    • @ArjanCodes
      @ArjanCodes  2 года назад +1

      Thanks so much! And will do 😊

  • @JoshSmeda
    @JoshSmeda 2 года назад +3

    I really love your videos on these subjects - keep it up!

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Glad to hear, Joshua - and I will ;).

  • @JorgeEscobarMX
    @JorgeEscobarMX 3 месяца назад

    I'm re-watching this video after a year and now I understand the entire thing. Specially the slots parameter, that flew over my head a year ago.😊

  • @JohnnysaidWhat
    @JohnnysaidWhat 2 года назад

    Great video really interesting topic had no idea the data class decorator existed. Just a small suggestion. The top end eq on your voice is a little shrill. DeEsser or small eq to lower the high freq bands. Thank you for this video all the same!

  • @christopheanfry
    @christopheanfry Год назад

    Thank you so much for this video and for the design guide I’ve just download, it’s literally gold 🙏

    • @ArjanCodes
      @ArjanCodes  Год назад +1

      You’re welcome! Glad you find it helpful.

  • @Saidffff
    @Saidffff 2 года назад +2

    Nice one Arjan!
    Also, __slots__ give faster attribute access AND space savings in memory due to switching to a more compact data structure. When you create many instances of the class, that is another advantage. Got that from reading 'Python distilled', written by the venerable David M. Beazly.

    • @chswin
      @chswin 2 года назад +3

      Lol a python dev worried about memory allocations…

  • @rrestituti
    @rrestituti Год назад

    Amazing video. I didn't know dataclasses and I found it amazing. Thanks, Arjan . Got a new subscriber.

    • @ArjanCodes
      @ArjanCodes  Год назад

      We're glad to have you, welcome aboard!

  • @aminramazanifar9743
    @aminramazanifar9743 2 года назад

    The final note about slot was really great.
    Thanks

  • @mauisam1
    @mauisam1 2 года назад +4

    Again Arjan, another fantastic video. If I become half the programmer you are I will be lucky. But I just have the love of programming so I will continue to work on improving my knowledge and skill set. So many programmer say just read the Docs, but I learn from examples and the Docs usually have few if not poor examples. So a big part of my improvement will be in thanks to your love of sharing your knowledge. Thank you...

  • @anthonvanderneut
    @anthonvanderneut Год назад +1

    13:31 Would it not be more useful to freeze the dataclass after calling __post_init__ , so that it errors on assigning "Arjan" instead of setting the (internal attribute) _search_string?

  • @auroraRealms
    @auroraRealms 2 года назад +81

    Although I like the ability to learn and use Data Classes. All my years of database programming has taught me to use JSON, and Dictionaries as much as possible. Especially in Web Services. The caveat to using Data Classes is that; changing a column type, name or description, or adding or removing columns ends up as a use case/feature ticket for the programmer which can take a bit of time to run through the development cycle. These column changes are guaranteed to happen all the time, in the life cycle of the product. A second problem, is that the code must be completely thrown out, when starting a new product. Using Dictionaries very often can allow these column changes from config files without recompiling or restructuring the code base. Going back to Web Services. Dictionaries can be web requests and responses, in JSON, without translation. This makes for high performance, and easy maintenance in the life cycle of product. It also makes copying and pasting the code directly into other products a possibility.

    • @duaneatnofroth
      @duaneatnofroth Год назад +15

      I checked out your channel in hopes to see some examples of the techniques you mentioned in your reply above. I think you might get a good response if you ever decide to do some programming videos. I'd love to see some from you.

    • @fabio.1
      @fabio.1 Год назад

      👀

    • @GankThat
      @GankThat 11 месяцев назад +1

      ​​@@duaneatnofrothhe doesn't need to give examples when what he's stating is already best practice when working with data

  • @shotihoch
    @shotihoch 11 месяцев назад

    And again... VERY interesting. Started as video for tea-brake, finished in my obsidian, writing down some very interesting tips. Thanks.

    • @ArjanCodes
      @ArjanCodes  11 месяцев назад +1

      I'm glad you found the video useful! :)

  • @robboerman9378
    @robboerman9378 Год назад

    I love your concise and clear explanations. Going to look into your course!

  • @nyghl
    @nyghl 2 года назад

    It was fun to follow along and learn! Thank you ArjanCodes.

  • @jaa928
    @jaa928 11 месяцев назад

    Thank you for the clear and concise explanation. As an experienced programmer, but newcomer to python this was an excellent, example-driven discussion.

    • @ArjanCodes
      @ArjanCodes  11 месяцев назад

      Happy you enjoyed the content!

  • @davidlakomski3919
    @davidlakomski3919 2 года назад

    I've tried 2 days ago to make a package to manage state of jobs with Pydantic, and even if it was less messy than what I did before, I realize now how easier and cleaner it would have been with dataclasses ! Thanks for the excellent content !

    • @ArjanCodes
      @ArjanCodes  2 года назад +1

      Glad it was helpful, David!

  • @qrubmeeaz
    @qrubmeeaz 2 года назад

    ... aaand he's done it again!! Brilliant! Thank you.

  • @marknielsen4494
    @marknielsen4494 Год назад

    Super high quality content - thank you Arjan!!!

  • @Andremzsptm
    @Andremzsptm 2 года назад

    Excellent video as always @ArjanCodes!

    • @ArjanCodes
      @ArjanCodes  2 года назад +1

      Thanks Andre, glad you liked it!

  • @nusermane1076
    @nusermane1076 2 года назад

    Incredibly good explanation, will try this for myself tomorrow 👍👍👍

  • @matthewnuzzaco2849
    @matthewnuzzaco2849 2 года назад

    This was super helpful, I used some of these tips almost immediately.

  • @arunny9430
    @arunny9430 2 года назад +1

    can you please give an example of when it would be a advisable to have kw_only = True? What advantages would it provide?

    • @ArjanCodes
      @ArjanCodes  2 года назад +2

      I think it's helpful in particular if you have several arguments that are easily mixed up.
      For example, if you have a class EmailMessage(from: str, to: str, message: str) and you call it in the code without keywords, it's hard to make sense of what is the from address and what is the to address. Having to provide them as keyword arguments avoids that problem and ensures that the code is easier to read.

  • @borisvujicic7817
    @borisvujicic7817 2 года назад +4

    This is great. ArjanCodes, have you thought about doing a video about Python descriptors? I think it could be very useful, as there is no good ones on RUclips.

    • @johntamplin
      @johntamplin 2 года назад

      Take a look at the videos by Corey Schaffer. A very different style, but equally good, in my opinion. I believe he did one on Python descriptors.

  • @justinpeter5752
    @justinpeter5752 2 года назад +2

    Very good video. I think I learned a lot about classes in this video and I can see where I can use some of these in my code. Well I’m not quite there yet with building classes with multiple inheritance to worry about the issue with slots. But at least I’ll start using slots for performance improvements. Overall, bravo. I’m starting to understand more about Python from a systematical perspective.

  • @christensencode7538
    @christensencode7538 2 года назад +4

    Your videos on dataclasses are awesome! I've used them for a few projects and they really help.

  • @MarkHimsley
    @MarkHimsley 2 года назад +3

    At 13:28 the exception is that the __post_init__ cannot assign to _search_string in your frozen data class, not that you were setting the name to Arjan after the data object was constructed. So it looks like using __post_init__ to create calculated fields from the initialised data is not going to work.

    • @MrGeordiejon
      @MrGeordiejon Год назад

      Another video explains this and how you can use ```object.setattr(self, value)```
      I spotted that too and looked before commenting - 👍

  • @cheesecake_mafia
    @cheesecake_mafia 6 месяцев назад

    I think you might find this interesting if you don't already know, but you can define class variables while using @dataclass. You just need to import ClassVar from typing and then when you are defining the class variables, use ClassVar after the colon and then put square brackets and the datatype of the class variable. I think this feature was mentioned in the documentation and also Tech with Tim channel helped me realise this. Great Video! Cheers.

    • @ArjanCodes
      @ArjanCodes  6 месяцев назад

      Interesting, didn’t know that was possible. Thanks for sharing!

  • @aungkyawkyaw9114
    @aungkyawkyaw9114 2 года назад

    next level! Thanks Uncle Arjan.

  • @jma42
    @jma42 2 года назад +1

    I also want to add that you can actually use asdict method from dataclasses and from_dict method from dacite library. It works as it sounds to be and even works in nested dicts/dataclasses!

  • @Kirac322
    @Kirac322 2 года назад +1

    Great video Arjan! Learned quite some new things even though I regularly use dataclasses.
    One suggestion which I encounter quite often in data science: Where and when to properly calculate additional properties (features for my models) after first initialization when there are dependencies between multiple objects, e.g, you have to wait for both to finish initialization, then calculate features. I'm currently working with a hirarchy of dataclasses and calculate these properties in the top level in __post_init__ but am unsure if that's the best way. Thanks!

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks so much, glad it was helpful!

  • @MichaelMorenoPhilosophy
    @MichaelMorenoPhilosophy 2 года назад

    I think 5:15 is wrong as those are not class variables, they're member annotations as per PEP 526. Initializing them on the same line would make it them class variables though.

  • @NdamuleloNemakh
    @NdamuleloNemakh 2 года назад

    Exactly what I've been thinking all along, "strict mode" is a feature that must be seriously considered

  • @abdelkadergnichi6643
    @abdelkadergnichi6643 Год назад

    You are awesome man i really appreciate you work bro your videos are so clear and beefy ❤❤

  • @SiarheiAkhramenia
    @SiarheiAkhramenia 5 месяцев назад

    My God, what an incredible sound quality!

  • @f4bglv
    @f4bglv 2 года назад

    Excellent video, very informative, concise and enjoyable... as always! Thanks again.

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks so much Fabio, glad the content is helpful!

  • @XCanG
    @XCanG 2 года назад

    I use similar thing when working with fastapi, library named SQLModel, what it basicaly is very similar to dataclass, but it has validation from pydantic, so if you, say assign to person with a name type int, like Person(name=1), then you get ValidationError exception. It is more useful in fastapi as it may be used as a mechanism to prevent API being called and executed if provided arguments are not match. And you can have more validation methods in Field, like: le, ge, lt, gt; for list types you may provide min/max range, for strings you may add regex or even something more custom via function.
    I like it a bit more than just dataclass

  • @NickWindham
    @NickWindham Год назад

    “Strict mode” will be called Mojo 🔥

  • @seans9168
    @seans9168 2 года назад

    Great overview and useful examples! Thanks for the video.

  • @ChrisBNisbet
    @ChrisBNisbet 2 года назад +7

    Hmm, freezing the data class resulted in an error when trying to set up _search_string, which is probably not what you want.
    Did I read the error output correctly?

  • @AlanHernandez-mw6xb
    @AlanHernandez-mw6xb 2 года назад

    This was actually very entertaining. Thanks!🎃

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks so much Alan, glad you liked it!

  • @JPy90
    @JPy90 2 года назад

    Awesome man.! Just arrive to your channel. Seems amazing

  • @alejandropereira5680
    @alejandropereira5680 2 года назад

    Very useful explanation, to the point and with real use case, really liking these vids

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks so much Alejandro, glad you liked it!

  • @mattcauth
    @mattcauth 2 года назад

    Very, very useful and well done. Thank you!

  • @aadithyavarma
    @aadithyavarma 2 года назад +5

    At 13:27, the error is that, it cannot assign the value to _search_string which we made in __post_init__(), so how do we assign values in __post_init__ when the dataclass is Frozen? Do we not declare it in the beginning and create a new member named _search_string only on __post_init__() ?

    • @korn6657
      @korn6657 2 года назад +1

      I solved it by using Object.__setattr__ on the instance.
      I would say that it's hacky way to do it, though. Since it means you are doing something wrong if you have to do things like this.

    • @aadithyavarma
      @aadithyavarma 2 года назад +1

      @@korn6657 Thanks for this tip. And I agree, this really shouldn't be encouraged just because it is possible.

  • @thomasoa
    @thomasoa 2 года назад +59

    The error you got one the frozen case was not when you set .name = “Foo”, but in the __post_init__ method, setting _query_string. Is there any way to do post_init when using a frozen dataclass?

    • @yakkayakka360
      @yakkayakka360 2 года назад +1

      I noticed that too. Glad I'm not the only one. Did you ever get an answer?

  • @rablaze
    @rablaze 2 года назад

    Love the videos! I was watching a rerun of a Supernatural episode while watching this and the actor that plays Crowley and you kinda like alike lol

    • @ArjanCodes
      @ArjanCodes  2 года назад

      LOL, I see what you mean :).

  • @fuadpalchayev7269
    @fuadpalchayev7269 Год назад

    Thank you Arjan!👍

  • @NicolasDumazet
    @NicolasDumazet 2 года назад

    At 13:27 it looks like the error you get is not because of mutation of a final dataclass after init. The trace points to __post_init__ unhappiness during the initial Person() construction

  • @flynnowen2478
    @flynnowen2478 2 года назад +15

    Love your content Arjan! I've been making an effort to apply your teachings as much as possible in my code.
    Would you consider doing any future videos on unit testing? I think it would be super useful. I personally use pytest, but you might know better frameworks.

  • @angelhdzdev
    @angelhdzdev 2 года назад

    Great video on Dataclasses! Thank you!
    Sadly, I had to learn with the docs, then this video popped up... :)
    +1 for the usage of type annotations. ;)

    • @ArjanCodes
      @ArjanCodes  2 года назад

      Thanks so much, glad the content is helpful!

  • @AndreyPutilov
    @AndreyPutilov 2 года назад

    Great explanations! Thanks for the content!

  • @marcioneto3016
    @marcioneto3016 2 года назад +10

    Amazing video, as usual. Here's a suggestion: how about a video on the infamous Visitor pattern next? Thanks for the amazing content. I really liked the Software Designer Mindset course, by the way.

    • @ArjanCodes
      @ArjanCodes  2 года назад +1

      Thanks for the suggestion, Márcio, and glad to hear you enjoyed the course!

  • @NeumsFor9
    @NeumsFor9 Год назад

    Do you do a video on the impact of slots on bulk data engineering?

  • @wv1138
    @wv1138 2 года назад

    Good point about a possible strict mode

  • @BSK_Rick
    @BSK_Rick 22 дня назад

    The most surprising thing is to realize that you actually type your code at that speed and you don't speed up in the video editing

  • @Giuseppe141992
    @Giuseppe141992 11 месяцев назад

    Thank you, this channel is an hidden gem.

    • @ArjanCodes
      @ArjanCodes  11 месяцев назад

      I'm glad you enjoyed the content!

  • @agnichatian
    @agnichatian 9 месяцев назад +1

    Scrutinizing your error code printout @13:29, It seems like a design flaw to not allow even __post_init__() to change the fields.

  • @fvbakel
    @fvbakel 2 года назад +2

    Great overview of the dataclass. I wonder what your view is on binding the dataclass to a SQL database. Is there an easy way? It seems that the Django and sqlalchemy methods are not compatible with the dataclass?
    Further more, what do you think about nested dataclass and the impact on hashing?

  • @anonymous102592
    @anonymous102592 10 месяцев назад

    Thanks , great explanation, and overview

    • @ArjanCodes
      @ArjanCodes  10 месяцев назад

      Thank you for the kind comment!

  • @serhiikroshka893
    @serhiikroshka893 Год назад

    Great overview. Thanks.

  • @JoshPaulie
    @JoshPaulie 2 года назад

    If you're printing an object you'd expect the repr to be printed, not str, no? Thanks for videos! Enjoying this one on my lunch break 😋 Every few seconds I find myself yelling "wait what?!" Learned a lot!!

  • @SystemSigma_
    @SystemSigma_ 2 года назад

    Nice overview of dataclasses.. Next, we need an extensive video about the testing frameworks and mocking for TDD!

  • @Elian_Amselem
    @Elian_Amselem 2 года назад

    what a nice theme, what's it called?
    i use python and never hear about dataclasses, very well explained! :)

  • @danieleatzeni2437
    @danieleatzeni2437 2 года назад +49

    Hey man, cool video! I saw that when you set frozen=True, you got an error in the __post_init__ (not in the main). Is there a way to use __post_init__ for frozen dataclasses?

    • @funkmedaddy
      @funkmedaddy 2 года назад +7

      I ran into this issue some time ago, apparently u can't do it directly since that would require you to change the object which is prohibited by the frozen=True statement (according to documentation __setattr__ and __delattr__ methods are added which will throw the error). But u can get around that using object.__setattr__(self, 'field_name', field_value) which is whats happening in the __init__ anyways (i guess it circumvents the __setattr__ method defined in class and calls the definition directly from the object class)

    • @LeteFox
      @LeteFox 2 года назад +3

      you can use super().__setattr__("_search_string", f"{self.name} {self.address}")

    • @funkmedaddy
      @funkmedaddy 2 года назад +1

      @@LeteFox yes as long as the super class isn't frozen itself, altho if you're not inheriting from anything it's more concise

    • @kunedroid3446
      @kunedroid3446 2 года назад +1

      I was just on this issue too...
      I don't know mate, it seems that python is trying too hard to add features which it was not well planned to and we are ending up with so many esoteric rules/details that learning python by anything other than reading books on "how to adhere to the pre-defined rules/standards of keywords" will soon be impossible..

    • @ArjanCodes
      @ArjanCodes  2 года назад +19

      I would actually use a different approach altogether if you want a frozen dataclass, but still would like to have a search string like in the example in the video (didn't have time to cover this because the video was already quite long).
      I wouldn't store the search string in an instance variable, but use a property instead. It would mean that you need to compute the search string on the fly every time though, so it might not be the preferred solution if you need to access it often, but I think it is a lot cleaner than circumventing attribute assignment using __setattr__.

  • @yiyangzhang608
    @yiyangzhang608 2 года назад

    very practical and useful, help me a lot, thank you🍗