Closures in Python | Explained with animations

Поделиться
HTML-код
  • Опубликовано: 26 июн 2024
  • In this Python programming tutorial, we will learn how closures work in Python. We will also see how shared extended scopes and multi-scoped variables are implemented in Python using intermediary cell objects. Understanding closures helps us in understanding other language features like function decorators.
    References
    ------------------
    * Python data model: docs.python.org/3/reference/d... - documentation for 'co_*' attributes can be found under "Code objects"
    * Cell objects: docs.python.org/3/c-api/cell....
    * Dr. Fred Baptiste's course www.udemy.com/course/python-3...
    Recommended prerequisite
    --------------------------------------------
    Variable scopes and Namespaces: • Python tutorial: Varia...
    Chapters
    ---------------
    0:00 Prerequisites
    0:12 First example code
    0:51 Visual representation of first example
    2:23 Closure
    3:12 second example
    4:26 Multiple closure instances
    4:51 Comparing with classes
    5:25 Shared free variables
    5:54 Cell objects
    7:01 attributes of function objects

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

  • @faramarztayyari3734
    @faramarztayyari3734 2 года назад +18

    A weird question pops into my mind, what percentage of Python programmers really know this level of in-depth knowledge in the real world?

  • @bhushandhuri2660
    @bhushandhuri2660 Год назад +8

    After listening to your video at 0.75 times and doing back and forth multiple times I finally understood the closure completely.
    Thanks for the video.👍👍

  • @hilmandayo
    @hilmandayo 2 года назад +14

    This is high-quality material!!! Keep up the good work! I hope this channel will grow more and can help others.

  • @doresearchstopwhining
    @doresearchstopwhining 4 месяца назад +1

    These videos are AMAZING. I have watched a lot of python content but IMO this is honestly the best. Not brushing over anything - very technical and the animations are top notch. Fantastic work and thank you so much. You should put up a donate link!

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

    High quality, Clarified my doubts.

  • @ulysses_grant
    @ulysses_grant 3 года назад +3

    This is great. Absolutely great.

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

    I like your way of teaching with visuals. Really helpful!!

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

    Great video, deep info. I had to watch at 0.75 speed cuz so deep.

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

    Nice video! Although a little bit too fast. Thanks!

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

    awesome explanation, really helpful. I look forward upcoming video!!!

  • @LamNguyen-nm1fq
    @LamNguyen-nm1fq 2 года назад

    This is great, bro. I've followed your channel.

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

    a very good video. I would request you to make a whole python playlist for intermediate to advanced level. You have a very unique way to explaining that make it easy to comprehend.

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

    Amazing stuff!!!

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

    awesome explanation❤‍🔥 thanks a ton for creating such quality content in best way to make difficult topics easy to understand with deepest explanation 💯

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

    great explanation good animations, keep on!

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

    awsme!! hope u are doing more such videos ..

  • @ThienNguyen-lh3bj
    @ThienNguyen-lh3bj 2 года назад +3

    Love this :3

  • @RahulSharma-lw2ss
    @RahulSharma-lw2ss Год назад

    excellent

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

    good video, the animations are helpful

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

    Amazing.. Sreekant, can you please tune voice over a little bit? I am using 0.75 but still sometimes few words are very fast. And more videos please :). Keep up the good work.

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

    would love to connect and see more videos !

  • @M.I.S
    @M.I.S 2 года назад

    thank YOU!

  • @dr.strangelove5622
    @dr.strangelove5622 Год назад +3

    This is an amazing video!! Excellent explanation and animations!! I have subscirbed to you!! By the way, which software do you use for these animations?

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

    best explaination

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

    5:08 to me, an object is a thing that has methods, like
    counter.increment()
    To me, it's counter-intuitive to say
    my_inc.increment()

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

    You can do this:
    def counter(num):
    def increment(inc=1):
    nonlocal num
    num += inc
    return num
    return increment
    counter10 = counter(10)
    closureList = [counter10(3) for a in range(0, 5)]
    print(closureList)
    to output this:
    [13, 16, 19, 22, 25]
    However, if you don't return num in the inner function, the output (and the list) will be:
    [None, None, None, None, None]
    because the inner func is returning nothing, i.e, is returning "None" in each iteration

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

    4:27 If `counter` no longer exists, why is it mentioned when we inspect the value of `my_inc`?

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

    Can u make a video bout python's generators/iterators memory layout

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

    What are the use cases of closures in python?

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

      It's the base for decorators. For example, you could implement a basic equivalent of '@functools.lru_cache' using a dictionary as the free variable.

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

      @@sreekanthpr a beginner (which I assume OP is based on his question) has no idea what you just said in your example.

  • @Han-ve8uh
    @Han-ve8uh 2 года назад

    At 3:50 the arrow pointed to 5 directly, but at 6:45 it pointed to a memory address which in turn points at 5.
    Is this an actually difference or because you didn't want to complicate things and animated the easy way at 3:50?
    3:50 example was using start+=step and 6:45 example (cell object) was using start=start+step, is this what is causing the difference?
    I ran both examples and observed their co_freevars, closure, co_varnames and they look exactly the same. This makes me think the arrow at 3:50 should also be pointing at a memory address like 6:45 and start+=step vs start=start+step has no difference in this lesson.
    If this is right, why complicate things using 2 different syntax, if wrong, what differences does += vs + cause in terms of closures?

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

      At all times, Python stores pointers to actual objects and Python takes care of automatic dereferencing (explained in another video ruclips.net/video/0Om2gYU6clE/видео.html, also mentioned at 1:33 in the current video). At 6:45, instead of this one hop, there are two hops. Sometimes I just directly show the value because it's easy, requires less space on the screen, and that part is not what I will be explaining at that point in time.
      With respect to '+=', there is a difference in how augmented arithmetic operators are handled(explained here ruclips.net/video/0Om2gYU6clE/видео.html). But for immutable objects, end result will be same. I just wanted to make it explicit.

    • @Han-ve8uh
      @Han-ve8uh 2 года назад

      @@sreekanthpr ​ @Sreekanth Thanks for your reply, i have watched the other videos too, really grateful that you make such clear animations to help learners.
      I understand the difference between += and + from that other video, but when it comes to this video, I still wish to reiterate my question.
      1. Why is 3:50 1 hop and 6:45 2 hops?
      2. Is the difference in 1. caused by writing start+=step vs start=start+step?
      3. Is start+=step vs start=start+step used to demonstrate some other closure related concept in this video if it doesn't cause 1.?

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

      Thanks!
      There is no difference in start+=step vs start=start+step in closure. I just wanted to emphasize the right-hand side is evaluated first and it gets assigned back to the 'start' variable, that's why I chose to write it explicitly.
      At 3:50 also there are 2 hops (the cell object exists). But the viewer is assumed to be not aware of the existence of cell objects at that point in time. At 06:32 is where I introduce this internal implementation detail.

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

      @@sreekanthpr Hey, I got everything that you said except for the definition of "closure". It's unclear whether "inner" is a closure. If the enclosed function _(enclosed inside another function, in this case, "inner")_ contains free variables, only then it's a closure, right? I think there are some technical details that I am not able to manacle.
      _PS: This is high-quality, quintessential content. I am looking forward to "Classes and Objects", "Decorators", "Metaclasses", etc. Also, you should start making videos on Data Structures and Algorithms with Python. I was always interested in the implementation details of CPython. May you achieve 10 million subscribers! I wish you the best of luck!_ :-)

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

      @@nirajraut9408 Yes, the "inner" function is a closure if it it references any variable in its nonlocal scope. Those variables are called "free variables". So, closure is "function + free variables" (or "function + environment")
      Next video might be on Python's import system covering things like module objects. After that I'm thinking of starting series on data structures.

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

    Dude , When are you going to upload new video ?

  • @adifirdaus8204
    @adifirdaus8204 Год назад +4

    too fast bro

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

      I'm adding higher pauses between sentences in newer videos.

  • @yt-1161
    @yt-1161 2 года назад

    I needed for this 8 min video around 40 min to watch. I still don't get everything

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

      I had to pause it every few seconds. It's just too quick and full of specialized terminology. Using pause by lector would be beneficial as it would give us time to assimilate the knowledge. I liked the drawings though. :)

  • @rahulmistry5381
    @rahulmistry5381 Месяц назад

    Video is nice but speak little slower.

  • @tejas4054
    @tejas4054 2 месяца назад

    Hindi me channel shuru kar ,,,nhi to nhi samzega kuch