7 Functional Programming Techniques to Enhance Your Python Code

แชร์
ฝัง
  • เผยแพร่เมื่อ 26 มิ.ย. 2024
  • In this video, I'll walk you through 7 functional programming techniques and demonstrate how they work. Although Python is not a purely functional language, functional programming can significantly improve your Python skills.
    🔥 GitHub Repository: git.arjan.codes/2024/func
    💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
    📨 The Friday Loop by ArjanCodes Newsletter: thefridayloop.com
    💻 ArjanCodes Blog: www.arjancodes.com/blog
    ✍🏻 Take a quiz on this topic: www.learntail.com/quiz/ezhdob
    🎓 Courses:
    The Software Designer Mindset: www.arjancodes.com/courses/tsdm
    The Software Architect Mindset: www.arjancodes.com/courses/tsam
    Next Level Python: Become a Python Expert: www.arjancodes.com/courses/nlp
    The 30-Day Design Challenge: www.arjancodes.com/courses/30ddc
    👍 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!
    Social channels:
    💬 Discord: discord.arjan.codes
    🐦 X: x.com/arjancodes
    🌍 LinkedIn: / arjancodes
    🕵 Facebook: / arjancodes
    📱 Instagram: / arjancodes
    ♪ Tiktok: / arjancodes
    👀 Code reviewers:
    - Yoriz
    - Ryan Laursen
    - Dale Hagglund
    - Kit Hygh
    - Alexander Milden
    - Bean
    🎥 Video edited by Mark Bacskai: / bacskaimark
    🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes
    🔖 Chapters:
    0:00 Intro
    0:32 #1. Recursion
    4:45 #2. Structural Pattern Matching
    6:17 #3. Immutability
    8:49 #4. Pure Functions
    11:11 #5. Higher-Order Functions
    15:53 #6. Function Composition
    18:42 #7. Lazy Evaluation
    20:47 Outro
    #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!

ความคิดเห็น • 84

  • @ArjanCodes
    @ArjanCodes  3 วันที่ผ่านมา

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

  • @TobyDillman
    @TobyDillman 6 วันที่ผ่านมา +33

    Bold of you to assume I'm going on any dates.

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา +14

      I have high expectations 😉

    • @saitaro
      @saitaro 6 วันที่ผ่านมา +13

      Arjan himself liked your comment on TH-cam, who could reject you after that?

    • @saitaro
      @saitaro 3 วันที่ผ่านมา +4

      Two days ago he liked me too, now I'm married with children. Think about it.

    • @ArjanCodes
      @ArjanCodes  2 วันที่ผ่านมา +2

      I’m really scared now to find out what happens if I remove that like.

    • @saitaro
      @saitaro วันที่ผ่านมา

      @@ArjanCodes Don't.

  • @cjdaniels4
    @cjdaniels4 5 วันที่ผ่านมา +5

    This is a nice, concise overview of some core, simple, practical functional concepts. I just want to make one note about your section on function composition. Notice at 16:33, Copilot suggests an implementation of the compose function for exactly 2 functions, which applies the functions in the correct order (based upon the mathematical definition of function composition). Specifically, the composition of functions f and g, which would be called as compose(f, g), first applies g (the right hand function) to an input (x), and then applies f to the result (i.e., compose(f, g)(x) == f(g(x))). However, the compose function that you instead implemented, taking any number of functions of type Composable, applies the functions in order from left to right, not right to left, because reduce traverses the list of functions from left to right. Therefore, your resulting compose function is not truly composing functions in the mathematical sense, and is generally called by other names in other languages (e.g., foldl or pipe) or even in existing functional Python libraries. For your compose function to behave similarly to the original Copilot suggestion, you would need to traverse the list of functions from right to left. This is also evidenced by the fact that in your original code leading up to your introduction of function composition, you had the expression (at 15:10) sort_fn(add_10(multiply_by_2(data))), but then (at 18:22) had to reverse the order of the functions in compose(multiply_by_2, add_10, quick_sort) to get the same result because your compose function applies the function in the reverse ("wrong") order.

  • @DrGreenGiant
    @DrGreenGiant 5 วันที่ผ่านมา +3

    Worth noting that copy() only returns a shallow copy. So it's a new list but if the original elements were mutable (yours were ints at that's fine) then modifying them in the new list will also modify them in the old list. This can be a big gotcha in parallel code.
    Deepcopy from the copy module is _almost_ always what you need when you need an expensive copy of non fundamental types.

  • @TheUpriseConvention
    @TheUpriseConvention 6 วันที่ผ่านมา +7

    Recently tried out Gleam was super fun! Python is my main language so really cool to see these ideas in Python, great timing Arjan!

    • @ArjanCodes
      @ArjanCodes  2 วันที่ผ่านมา +1

      Glad you enjoyed it!

  • @BenjaminMorrison-pz2in
    @BenjaminMorrison-pz2in 4 วันที่ผ่านมา

    in the bubble sort, the inner loop starts from the outer loop starts which means that there are a subset of elements in the beginning that are not sorted.

  • @victoradukwu2719
    @victoradukwu2719 5 วันที่ผ่านมา +1

    As always, it's another masterpiece. Thanks, Arjan.
    I believe the input ‘data’ at 20:09 could still be a list, instead of an iterator; Only the return needs to be an iterator
    In addition, we can still achieve the lazy evaluation 20:24 by simply using the result of the map function, without casting into a list

  • @benfung9571
    @benfung9571 6 วันที่ผ่านมา +1

    This is really spot on
    I was struggling with function composition for awhile

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Glad you enjoyed it!

  • @thisoldproperty
    @thisoldproperty 5 วันที่ผ่านมา +2

    Really enjoyed this video. The advanced concepts are appreciated.

    • @ArjanCodes
      @ArjanCodes  2 วันที่ผ่านมา

      Glad you enjoyed it!

  • @djupstaten2328
    @djupstaten2328 4 วันที่ผ่านมา

    I find elimination of state to be mostly an obstacle in concurrent programming because atomic operations make threads inherently agnostic of what's going on and whether they should do a/b/c depending on updated conditions, and it also makes it difficult for them to broadcast their own state as it will require an intermediate who would ultimately end up doing exactly what that thread could be doing autonomously (and with less context). It's not impossible to safely allot partitions of a shared workload or state object by using range/slice-types for instance while retaining communicability.

  • @shalomdosseh5367
    @shalomdosseh5367 6 วันที่ผ่านมา

    Always great and understandable videos. Thanks 🥲

  • @timelschner8451
    @timelschner8451 6 วันที่ผ่านมา

    As always Arjan, many thanks!

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      You’re welcome Tim!

  • @justinhall7022
    @justinhall7022 6 วันที่ผ่านมา

    Another great video. As a newbie, these really jelp to understand the important thingen. Thanks yuo!

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Glad to hear you liked it 😊

  • @sviteribuben7245
    @sviteribuben7245 6 วันที่ผ่านมา

    Thx Arjan! Partial is very useful! Its new for me😊

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา +1

      You’re welcome! 😇

  • @alejandrocarmena8767
    @alejandrocarmena8767 6 วันที่ผ่านมา

    Great video! It can be challenging to move all the print statements to the main function since you need to print intermediate results sometimes

  • @thomasroberts6008
    @thomasroberts6008 3 วันที่ผ่านมา +1

    I would argue at 20:09 the function parameter could be Iterable, and have the output be still be an iterator. This way anything that can be iterated over, lists or iterators (or anything implementing __iter__) can be passed and it don't need to cast my inputs with iter(...). I try and make my functions inclusive with Iterable inputs and Iterator outputs, unless there is a specific reason that doesn't work.

    • @ArjanCodes
      @ArjanCodes  3 วันที่ผ่านมา

      Great suggestion, that is a definite improvement over the type annotation I used.

  • @paper_cut9457
    @paper_cut9457 6 วันที่ผ่านมา

    Great tips for one of the greatest python style there is !

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Glad you enjoyed it!

  • @gpcureton
    @gpcureton 5 วันที่ผ่านมา

    I've been doing a lot of the stuff in this video in Rust, it's nice to see a Python implementation of the same ideas which I can start to use in my day job.

  • @ramimashalfontenla1312
    @ramimashalfontenla1312 6 วันที่ผ่านมา

    Niceeeeeeeee! Another super useful video!

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Enjoy! :)

  • @edgeeffect
    @edgeeffect 6 วันที่ผ่านมา +3

    0:28 "As a side effect..." I saw what you did there.
    Nice recursion example... quicksort is so much more likely to be used than factorial.

    • @maleldil1
      @maleldil1 4 วันที่ผ่านมา

      The vast majority of programmers aren't going to write quicksort either. In imperative languages like Python, you should likely default to using iteration whenever possible and only use recursion for obviously recursive problems (e.g. graph traversal). Even then, one must be careful about blowing up the stack, so it's important that you also know how to convert a recursive function into one that uses an explicit stack.

  • @tpag20
    @tpag20 2 วันที่ผ่านมา

    Using 'reduce' to apply functions sequentially seems complicated. Instead, using a monad class seems like a better way to handle exceptions and readability. Using the '__or__' method as a 'bind' method, we can use
    result = Monad(10) | add_ten | mul_two | div_zero
    like this. I'd love to hear your thoughts. I'd like to add that it doesn't fit the content of this video because you need to define the Monad class 😁

  • @andcarl85
    @andcarl85 5 วันที่ผ่านมา

    What do you think of compose from the funcy-package? I've used it instead of writing my own compose-function.

  • @devin865
    @devin865 6 วันที่ผ่านมา

    I loved the refactoring of the github copilot code. I have to do that too! 😂

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Yes, that happens a bit too often, haha.

  • @jamesarthurkimbell
    @jamesarthurkimbell 6 วันที่ผ่านมา

    Is your Copilot suggesting lines you've already typed in a practice run before filming? Or does it not remember context in that way, and these are "fresh" suggestions?

  • @saitaro
    @saitaro 6 วันที่ผ่านมา

    19:58 These both functions should take an Iterable as an argument, not an Iterator. Interpreter will automatically call for an iterator while using the for loop. Iterator protocol requires the __next__ method, which is not implemented for a list, for example. But the functions obviously can work with a list. We always should use the broadest types possible in for a function arguments and the most exact type for the result. This is known as the robustness principle, "Be liberal in what you accept, and conservative in what you return".

  • @ravenecho2410
    @ravenecho2410 5 วันที่ผ่านมา

    Great vid as always, theres also *functools groupby*, which seems pretty powerful like...
    Sqlite3 backend, really doesnt matter, but i found like:
    ```
    Select from table where x, and y order by a,b
    ;```
    Especially with um passing a method into the retrieval for how to create named tuples out of the list... you can get really ""complex"" behavior, with super performant code, thats also super readible.
    Ie used this in prompt generation for our tool, another thing im wondering about is separation vs interface vs api. For code that is being rapidly developped/iterated upon... (separation seems most important... i think.?)

  • @brudinie
    @brudinie 5 วันที่ผ่านมา +1

    Best dating advice ever

  • @Wolar94
    @Wolar94 6 วันที่ผ่านมา +2

    Great video! I have a question, can't you just do this instead:
    ```
    def multiply_by_x(data, x: int) :
    return map(lambda y: x * y, data)
    def add_x(data, x: int) :
    return map(lambda y: x + y, data)
    ```
    As map returns an iterator, similarly to yield from.
    So the same as your initial functions but do not cast it to list to iterate over the iterator, just return the iterator.

    • @askii3
      @askii3 5 วันที่ผ่านมา

      I was expecting him to simply return map, like you're suggesting. However, if you think about it, what he's doing is the same. At 20:00 he modifies the type hint for data to be an iterator. For loops use iterators without casting them to lists. The function is taking the data iterator as an input argument and returning a generator (iterator) by yielding from the for loop. So, there's no casting to lists and is true lazy evaluation.

    • @Wolar94
      @Wolar94 5 วันที่ผ่านมา

      @@askii3 Yes i know it's the same, it's just unnecessarily making the code abit harder to read.

    • @askii3
      @askii3 5 วันที่ผ่านมา

      @@Wolar94 I was mainly focused on your comment that he's casting to lists. When I first read that, I thought you were saying his newer functions using yield are casting to lists (which they are not). But now I see you were referring to the older functions that do cast to lists.

  • @malteplath
    @malteplath 6 วันที่ผ่านมา

    Can you show how you would deal with exceptions when you use function composition? Assume that the functions you want to compose could encounter division by zero or a TypeError or ValueError because you are processing data that is not (completely) under your control. For example when processing CSV files you may expect a certain shape from the first two lines, but you would have to validate the whole file to know that the number of entries is the same in every row. Add to that the fact that you may be calling 3rd party code in the functions you compose.
    How would you do the error/exception handling?

  • @hriscuvalerica4814
    @hriscuvalerica4814 6 วันที่ผ่านมา

    I rarely use recursion . Mostly to traverse a shallow tree like structure. Python has a recursion depth limit .

  • @JonitoFischer
    @JonitoFischer 6 วันที่ผ่านมา +3

    List comprehensions are more readable than map, readability counts.

    • @kaosce
      @kaosce 6 วันที่ผ่านมา +1

      Not the same goals. Map return an iterator so it is only run when iterating while list comprehensions create an actual list

    • @JonitoFischer
      @JonitoFischer 6 วันที่ผ่านมา

      @@kaosce wait what? He converted the result of the map function to a list, and you can always write a generator expression if you don't want the complete list and just the generator...

    • @JonitoFischer
      @JonitoFischer 6 วันที่ผ่านมา

      @@kaosce moreover, map, filter, lambdas were there even before list comprehensions, but at the end, readability counts.

    • @jamesarthurkimbell
      @jamesarthurkimbell 6 วันที่ผ่านมา +1

      The big difference for me is that you have to think of a name for the intermediate elements in a comprehension, e.g. [int(x) for x in numbers] or whatever, and sometimes that can really help. Other times, people's names are so vague or so misleading that they would have been better off with map.

    • @Wolar94
      @Wolar94 6 วันที่ผ่านมา

      Readability counts much more in real use cases. List comprehensions CAN get unreadable though, but as long as you keep them simple they are very easy to understand.

  • @entitledOne
    @entitledOne 5 วันที่ผ่านมา

    Your point 3 needs a asterisk with the solition. The copy methid creates a shallow copy. Ehich means that if your liat contains anything that's passed by reference, it will be the same in the new list. If those mutable elements are changed in the new list, they will also be changed in the old list. For true immutability, the deepcopy functionality should be used.

    • @ArjanCodes
      @ArjanCodes  5 วันที่ผ่านมา

      Good point!

  • @detemegandy
    @detemegandy 5 วันที่ผ่านมา

    I made a composable in my project recently, but it did not have type hint! I had the apply be a lambda, which is ugly IMHO. Then you solved it... but then another lambda appeared! I would want the return to be `partial(reduce, apply, functions)`! I will incorporate the type definition though!

    • @ArjanCodes
      @ArjanCodes  5 วันที่ผ่านมา +1

      Oohhh I like that!

    • @detemegandy
      @detemegandy 5 วันที่ผ่านมา

      Corrected in edit. Glad you liked it😁

  • @animeshsingh1307
    @animeshsingh1307 6 วันที่ผ่านมา

    Nice video! The subtitles are a little bit out of sync though. Please fix that. Thanks.

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      We’ll look into it, thanks!

  • @paulhetherington3854
    @paulhetherington3854 วันที่ผ่านมา

    That be -- TTY relay only -- in skrrpts!

  • @herrxerex8484
    @herrxerex8484 3 วันที่ผ่านมา

    reduce does beta reduction i believe

  • @GOTHICforLIFE1
    @GOTHICforLIFE1 6 วันที่ผ่านมา

    i still struggle to see the value of a compose function over a wrapper function that simply calls a series of functions sequentially. To me at least it feels much more readable and equally flexible. And if you rely on having so many arguments that in no longer remains readable it feels nicer to simply use a class instead. I do understand that the premise of the video is to utilise purely functional principles, but i really can't see a good use case for something like partial functions unless there's some underlying performance benefits.
    Even in languages like Go i mostly see the sequential approach against a struct of data which is also more readable imo. But then again i'm no expert in either languages, so that could just be lack of experience / use cases where this would make sense to apply

  • @Soltaiyou
    @Soltaiyou 6 วันที่ผ่านมา

    Love the mechanical keyboard 😂

  • @danielschmider5069
    @danielschmider5069 2 วันที่ผ่านมา

    Please stop using type hints if it starts accounting for half the video's runtime.

  • @doc7115
    @doc7115 5 วันที่ผ่านมา +2

    pure function is not necessarily idempotent, these are two totally irrelevant concepts, not sure why you said that. 9:02

  • @MLlRoon
    @MLlRoon 6 วันที่ผ่านมา

    Monad is insulted not being mentioned here

  • @sulfur32066
    @sulfur32066 6 วันที่ผ่านมา +10

    Please disable copilot 😂

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา +1

      I’m too lazy, haha.

    • @sulfur32066
      @sulfur32066 6 วันที่ผ่านมา

      @@ArjanCodes that’s how programming was invented:)

    • @DrGreenGiant
      @DrGreenGiant 5 วันที่ผ่านมา +1

      I really like copilot! It's good seeing it work and seeing it make mistakes

  • @paulosergioschlogl9550
    @paulosergioschlogl9550 6 วันที่ผ่านมา

    I like to use functions, however i dont use this kind of concepts 😮

  • @yomajo
    @yomajo 2 วันที่ผ่านมา

    No offense, but compose seems the kind of thing, sr devs would write to distance themselves from pleb devs. Respectfully, pleb dev.

  • @kilianklaiber6367
    @kilianklaiber6367 5 วันที่ผ่านมา

    Sorry, but this is Just too fast for me, too many concepts in extremely quick succession. I don't tink that you used the Term idempotent correcty, If this means the Same AS the mathematical definition.

    • @kilianklaiber6367
      @kilianklaiber6367 4 วันที่ผ่านมา

      The idea that the output should always be the same, if the input is the same, is just part of the mathematical definition of a function. Idempotent means that applying a function to itself renders the same result: f(f(x)) = f(x)

  • @mmilerngruppe
    @mmilerngruppe 6 วันที่ผ่านมา +3

    17:12 oh gods, they brought all that [T] cryptoshit from Java and C++ to my beloved Python. 😢

  • @y2ksw1
    @y2ksw1 5 วันที่ผ่านมา +1

    The usage of AI while programming can lead to terribly wrong code. I know, you like it because of the speed, but the moment you trust it blindly, you have lost the game.

  • @FeverYonge
    @FeverYonge 5 วันที่ผ่านมา

    I laugh at tutorial videos and people who watch them and think they are being productive wasting their time. When I was in a python network development internship, never ever found a video helping me, it was all going to documentation sites or asking people in forums. It doesn't matter cause like TechLead says, tech is almost dead nowadays, it just a skill for immigrants trying to immigrate in developed countries.

  • @caseybackes
    @caseybackes 6 วันที่ผ่านมา +1

    first...ah. not first. (sigh). i'll be first one day. congrats @ramimashalfontenla1312

    • @ArjanCodes
      @ArjanCodes  6 วันที่ผ่านมา

      Haha, keep at it! 💪