Podcast Lookup

StoicCodeCast 10 - Python Enum + Modules + Datetime + Decorators + Error handling + Deleting objects

StoicCodeCast

  • November 30, 2024
  • 14 min
Episode page
About this episodeEpisode #10, 2024-12-02 Get ready for a deep dive into a power pack of advanced Python topics! In this episode, we'll explore enums…

Episode #10, 2024-12-02

Get ready for a deep dive into a power pack of advanced Python topics! In this episode, we'll explore enums, modules, datetime manipulation, decorators, error handling, and object deletion. Whether you're looking to enhance your Python skills or tackle more complex programming challenges, this episode has something for everyone.

Follow up the podcast with the book.

The best way to send money abroad or have virtual cards: create a wise account and select a bonus!

Support our work.



Get full access to Stoic Coding at costa86.substack.com/subscribe

Transcript

From the publisher

This transcript comes from the podcast’s own feed, shown as the publisher wrote it.

StoicCodeCast 10 - Python Enum + Modules + Datetime + Decorators + Error handling + Deleting objects

00:00—
  1. Speaker 2

    Welcome back to Stoic Codecast. Ready for another deep dive into Python, street to the point.

  2. Speaker 1

    Always ready for more Python.

  3. Speaker 2

    If you haven't grabbed a copy of the book yet, you can find the link in the description. We're looking at Chapter 10 this time. It's packed with, well, ways to make your Python code cleaner, more organized, all that good stuff.

  4. Speaker 1

    Yeah. Even for someone who's been using Python for a while, there's a lot of good stuff in there, those aha moments.

  5. Speaker 2

    All right. So we're talking enums, modules, how to handle dates and times, decorators, and, of course, how to deal with errors. That's always fun.

  6. Speaker 1

    Essential stuff.

  7. Speaker 2

    Okay. So the book mentions this scenario, and I think we've all been there. You have a variable, and it can only be one of a few specific options, like imagine you're building a system and you need to track job titles.

  8. Speaker 1

    Without something like an enum, it can get messy fast.

  9. Speaker 2

    Exactly. People might enter a salesperson with a capital S or lowercase or maybe a salesperson all spaced out. Your data is a mess before you know it.

  10. Speaker 1

    Total inconsistency.

  11. Speaker 2

    So enums, they bring order to the chaos. You define those job titles, salesperson, software engineer, data analyst, whatever, as specific unchanging things, constants. Like the job position enum the book uses as an example.

  12. Speaker 1

    What I find really useful is you're basically creating a mini language within your code specific to your problem.

  13. Speaker 2

    Right. And it's so simple to do. Import enum from the enum module. Define your enum like it's a class that inherits from enum. Then just list your options.

  14. Speaker 1

    Salesperson, regional manager, whatever you need. All caps, which helps them stand out.

  15. Speaker 2

    Yeah. It's like a big sign saying, hey, this isn't just some random string. It means something specific. And then to use it, you reference it like job position, salesperson.

  16. Speaker 1

    And think about it, enums aren't just for job positions. User roles in an app, states in a game.

  17. Speaker 2

    Days of the week even. Anytime you have a limited set of options makes things way more structured.

  18. Speaker 1

    Definitely.

  19. Speaker 2

    Okay, so speaking of structure, let's talk modules. When your code base gets huge, trying to keep everything in one file.

  20. Speaker 1

    Oh, it's a nightmare.

  21. Speaker 2

    It's like trying to find a specific grain of sand on the beach. Modules let you split things up. Each file has its own purpose.

  22. Speaker 1

    Think of it like departments in a company. The book has this example, a directory with files like main.pi, infosales.pi, then infoaccounting.pi, each one handling its own thing.

  23. Speaker 2

    Yeah, and you connect them using imports.

  24. Speaker 1

    Yeah.

  25. Speaker 2

    Like you're building bridges between the different parts of your code. The book actually talks about four ways to import things.

  26. Speaker 1

    You've got the direct import, like from info.salesimportemployeeslist, get just what you need.

  27. Speaker 2

    Right. Then there's aliasing from info.salesimportemployeeslist as L, shorter to type.

  28. Speaker 1

    And then the wildcard import from info.salesimport. brings everything in, which can be a bit risky.

  29. Speaker 2

    Yeah, naming conflicts, all that.

  30. Speaker 1

    Exactly. And lastly, you can import the whole module. Import info.accounting. Access everything with dot notation.

  31. Speaker 2

    So many options.

  32. Speaker 1

    It's about finding the balance. Do you need everything? Just specific things. It's a design choice.

  33. Speaker 2

    Totally. Okay, let's move on to something everyone deals with. Dates and times.

  34. Speaker 1

    Python's date time module. It's like a super powered clock.

  35. Speaker 2

    The book goes deep on this one. Getting the current date and time with datetime.datetime.now. Formatting it different ways using StrifeTime.

  36. Speaker 1

    If you're building a calendar app, this is your best friend.

  37. Speaker 2

    Absolutely.

  38. Speaker 1

    Yeah.

  39. Speaker 2

    And you can calculate time between dates. Like, you know, figuring out how many days till your vacation.

  40. Speaker 1

    Date time dot time delta. Super useful for deadlines. All sorts of things.

  41. Speaker 2

    Right. And the book also mentions time zones. Super important when you have users all over the place. Zone info is what you use for that.

  42. Speaker 1

    You know, scheduling a meeting with someone in a different time zone used to be such a hassle calculating the difference yourself.

  43. Speaker 2

    Zone info just handles it for you. Yeah. So much easier.

  44. Speaker 1

    Definitely.

  45. Speaker 2

    Okay. So are you ready for something a bit more challenging, but also really rewarding?

  46. Speaker 1

    Hit me with it.

  47. Speaker 2

    Decorators. The book describes them as functions that modify the behavior of other functions, which I don't know about you, but that sounds a bit. Yeah. So what does that actually mean?

  48. Speaker 1

    Okay, think of it like this. You have a gift. That's your function. The decorator is the wrapping paper. Add something extra without changing the gift itself.

  49. Speaker 2

    Okay, I like that. So the book has this example, a decorator called Print Start Stand. Just prints a message before and after a function runs.

  50. Speaker 1

    The key is nested functions. You have this inner function, usually called wrapper. That's where the magic happens.

  51. Speaker 2

    And you apply the decorator with the at symbol, like tagging the function.

  52. Speaker 1

    What's cool is you can write a decorator once, then use it on tons of functions. Adds the same behavior without repeating code.

  53. Speaker 2

    Like instead of adding logging code to every single function, you have a decorator that handles it. Way cleaner.

  54. Speaker 1

    Exactly. The book even shows how to make decorators that take arguments even more flexible.

  55. Speaker 2

    This is definitely one of those things that might take a while to sink in, but the possibilities are huge.

  56. Speaker 1

    Oh, for sure.

  57. Speaker 2

    So now let's talk about the reality of coding. Things don't always go as planned.

  58. Speaker 1

    Errors. Gotta love them.

  59. Speaker 2

    The book uses some classic examples. Dividing by zero. Trying to access something that's not in a list.

  60. Speaker 1

    Things that'll crash your program if you're not careful.

  61. Speaker 2

    Right. And it introduces this structure. Try. Accept. Finally. It's like a safety net.

  62. Speaker 1

    You put the risky code in the try block. Then in the accept block, you say how to handle specific errors. Like, hey, Python, if this happens, don't freak out. Just do this instead.

  63. Speaker 2

    Yeah. The book mentions zero division error and index error, but there are tons of different types of exceptions.

  64. Speaker 1

    Yeah.

  65. Speaker 2

    And there's this syntax as E. Let's you actually look at the exception itself, get more information.

  66. Speaker 1

    Like what was the exact error message? What went wrong?

  67. Speaker 2

    Exactly. Then there's the finally block. This code always runs no matter what.

  68. Speaker 1

    Cleanup crew, no matter what the outcome.

  69. Speaker 2

    Right. Now there's also this keyword, pass. You can use it in an accept block if you don't actually want to do anything with the error.

  70. Speaker 1

    Book cautions against using it too much though.

  71. Speaker 2

    Yeah, it can hide problems.

  72. Speaker 1

    Yeah.

  73. Speaker 2

    Like sweeping dirt under the rug.

  74. Speaker 1

    But sometimes it makes sense, like if you're just sketching out your code and haven't figured out the error handling yet.

  75. Speaker 2

    Okay, so we've seen how to handle errors when they happen, but sometimes you want to make them happen on purpose.

  76. Speaker 1

    Control the chaos.

  77. Speaker 2

    Exactly. Python lets you do that with the raise keyword. The book uses this example, a function called introduce accountant. If you try to introduce someone who's not on the list, it raises a value error.

  78. Speaker 1

    Like a bouncer at a club, only certain people allowed in.

  79. Speaker 2

    So we've seen how to deal with errors gracefully, even make them happen ourselves. And what about cleaning things up, getting rid of stuff we don't need anymore?

  80. Speaker 1

    Digital decluttering.

  81. Speaker 2

    The Dell keyword deletes objects from memory, variables, elements from a list, keys from a dictionary.

  82. Speaker 1

    The book has some good examples of how to use it.

  83. Speaker 2

    But like with actual decluttering, you've got to be careful. Deleting the wrong thing.

  84. Speaker 1

    Can cause some major headaches.

  85. Speaker 2

    So use it wisely. Double check before you hit that delete key.

  86. Speaker 1

    Back again for more Python, straight to the point. Still on chapter 10, and things are getting interesting.

  87. Speaker 2

    Definitely more advanced stuff today.

  88. Speaker 1

    Ready to dive into generators?

  89. Speaker 2

    I've heard the term, but honestly, they've always been a bit of a mystery. What makes them so special?

  90. Speaker 1

    Think about it this way. You've got a massive data set, like way too big to fit in memory all at once. Generators let you deal with it in chunks, generate a value, use it, then move on to the next.

  91. Speaker 2

    So instead of loading the whole file, it's more like streaming a movie. You get what you need when you need it.

  92. Speaker 1

    Exactly. The book uses that countdown example. Remember, each time you call the generator, it gives you the next number in the countdown. The yield keyword is the key here. Pauses the function, remembers where it was, returns a value.

  93. Speaker 2

    It's like a function with a built-in pause button.

  94. Speaker 1

    And when you call it again, it picks up right where it left off. Super efficient for big data sets or even, you know, sequences that could go on forever.

  95. Speaker 2

    Infinite possibilities. Now, the book also mentions generator expressions. Are those like a shortcut for making generators?

  96. Speaker 1

    Kind of. They look a lot like list comprehensions, but instead of creating a whole list, they make a generator object.

  97. Speaker 2

    Subtle difference, but I guess it matters for memory usage, especially when you're dealing with tons of data.

  98. Speaker 1

    Huge difference. Python often gives you multiple ways to do things. Sometimes it's about readability, sometimes efficiency, sometimes both.

  99. Speaker 2

    Trade-offs.

  100. Speaker 1

    Always trade-offs. Okay, ready for another cool feature?

  101. Speaker 2

    Lay it on me.

  102. Speaker 1

    Lambda functions. Ever seen those in code?

  103. Speaker 2

    Oh yeah, but I never really understood them. They're just like tiny functions.

  104. Speaker 1

    Basically. Anonymous functions, they're also called. You define them in one line, perfect for when you need something simple, just for a short time.

  105. Speaker 2

    No need to write a whole function block.

  106. Speaker 1

    Exactly. The book uses the example of squaring a number, lambda x by 2. Super concise.

  107. Speaker 2

    I've also seen them used with things like map, filter, reduce.

  108. Speaker 1

    Ah, yes. Higher order functions.

  109. Speaker 2

    Which always sounded intimidating.

  110. Speaker 1

    Not really. So map, you want to apply the same function to every element in a list. Map lets you do that without writing a loop.

  111. Speaker 2

    So like squaring every number in a list. I could use map with a lambda function that squares the input.

  112. Speaker 1

    Exactly. Then you have filter. Think of it like a sieve. You give it a function that says true or false for each element, and it only keeps the ones that are true.

  113. Speaker 2

    So if I had a list of ages, I could filter for only those above 18 using a lambda function.

  114. Speaker 1

    Perfect example. And lastly, reduce. This one's a bit more specialized.

  115. Speaker 2

    The book says you need to import it from functools.

  116. Speaker 1

    Right. Reduce takes a function and an iterable, and it keeps applying the function cumulatively. Like, to sum all the numbers in a list, you'd use a lambda function that adds two numbers. Reduce keeps adding the result to the next number, and so on.

  117. Speaker 2

    So it kind of collapses the list down to a single value.

  118. Speaker 1

    Exactly. These higher order functions, they're all about functional programming, a different way of thinking about code.

  119. Speaker 2

    A whole different mindset.

  120. Speaker 1

    It might seem strange at first, but once you get it, it can make your code so much cleaner.

  121. Speaker 2

    More Pythonic, as they say.

  122. Speaker 1

    Exactly.

  123. Speaker 2

    Okay. Welcome back to Stoic Codecast for the last part of our deep dive into chapter 10. We've covered a lot of ground, but it's been mostly theoretical. Time to see how this stuff actually works in the real world.

  124. Speaker 1

    Right. Let's take those enums, modules, decorators, all those tools, and see how they fit into real projects. Make things cleaner, more efficient.

  125. Speaker 2

    So let's say we're building a web app. Something to manage employee data for a company. Where would we even start?

  126. Speaker 1

    Well, first thing that comes to mind, those enums we talked about. Perfect for representing different job titles. Just like the book's job position example. Software engineer, product manager, data scientist.

  127. Speaker 2

    Instead of freeform text fields where anyone can type anything.

  128. Speaker 1

    Yeah, which is just asking for trouble. Inconsistent data, typos, enums make it clear these are the only valid options.

  129. Speaker 2

    And you could use them for other things too, right? Like employee status, active, inactive, only, whatever you need.

  130. Speaker 1

    Absolutely. Makes your code more readable and it acts like a built-in check. This data has to be one of these values.

  131. Speaker 2

    Okay, so our app's going to grow. We're going to have tons of code. How do modules help us keep things organized?

  132. Speaker 1

    Modules are key for breaking a big project into smaller, manageable chunks. You might have one module for user authentication, another for employee data, another for reports.

  133. Speaker 2

    Each module has its own job.

  134. Speaker 1

    Exactly. And it means multiple developers can work on the project without stepping on each other's toes.

  135. Speaker 2

    Now, what about, let's say we need a feature to calculate how long an employee's been with the company. How does date time come into play?

  136. Speaker 1

    That's where date time shines. Get the current date with datetime.date.today, pull the employee's start date from the database, and then use datetime.timedelta to get the difference.

  137. Speaker 2

    And you can even format that difference nicely, right? Like Alice has been with the company for two years and five months.

  138. Speaker 1

    Straff time to the rescue. And of course, if you need to deal with time zones, ZoneInfo can handle that for you. Super important for global applications.

  139. Speaker 2

    Makes things so much simpler.

  140. Speaker 1

    Definitely.

  141. Speaker 2

    Okay, decorators. I'm curious how those would fit into this employee management app.

  142. Speaker 1

    Decorators are great for adding functionality to multiple functions without repeating yourself. Like, let's say you want to log every time someone updates an employee's record.

  143. Speaker 2

    Track those changes.

  144. Speaker 1

    Right. You could write a decorator called logAction, apply it to all the functions that modify employee data. It'll log those actions automatically without cluttering up your main function code.

  145. Speaker 2

    Keep things clean. So what about generators? When would we actually use those?

  146. Speaker 1

    Generators are all about efficiency. Imagine you need to generate a big report, something that involves processing data from thousands of employees.

  147. Speaker 2

    That could take a while.

  148. Speaker 1

    Instead of loading all that data at once, a generator lets you process it in smaller chunks, yield a result for one employee, then move on to the next.

  149. Speaker 2

    Ah, so it's not just about memory. It's about keeping the app responsive even when you're dealing with huge amounts of data.

  150. Speaker 1

    Exactly. And finally, those Lambda functions. They might seem small, but they're incredibly useful.

  151. Speaker 2

    Like for those little tasks where you don't want to write a whole function.

  152. Speaker 1

    Right. You could use a Lambda with the sort method to sort employees by last name or hire date, whatever. Or use it with map to extract specific data from a list of employees.

  153. Speaker 2

    Like their email addresses or departments.

  154. Speaker 1

    Exactly. So that about wraps up our exploration of chapter 10. We've covered a lot from organizing your code with enums and modules to handling dates and times to those powerful functional programming concepts.

  155. Speaker 2

    It's been a really great deep dive. If you're listening and you haven't checked out Python straight to the point, we highly recommend it. Link in the description.

  156. Speaker 1

    Definitely. Full of practical advice and written in a way that's actually enjoyable to read.

  157. Speaker 2

    And with that, I think it's time to wrap up this episode of Stoic CodeCast. Thanks for joining us, and until next time, happy coding!