Python Generators

Sdílet
Vložit
  • čas přidán 24. 07. 2024
  • Python generators are lazy sequences and pausable functions.
    ― mCoding with James Murphy (mcoding.io)
    Source code: github.com/mCodingLLC/VideosS...
    Generators as coros: peps.python.org/pep-0342/
    For loops vid: • For loops are redundant
    SUPPORT ME ⭐
    ---------------------------------------------------
    Patreon: / mcoding
    Paypal: www.paypal.com/donate/?hosted...
    Other donations: mcoding.io/donate
    Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, John Martin, Mutual Information
    BE ACTIVE IN MY COMMUNITY 😄
    ---------------------------------------------------
    Discord: / discord
    Github: github.com/mCodingLLC/
    Reddit: / mcoding
    Facebook: / james.mcoding
    CHAPTERS
    ---------------------------------------------------
    0:00 Intro
    0:16 Defining generators
    1:55 Iterators and Range
    3:49 File processing
    4:55 Lazy sequences and Collatz
    7:19 Generator comprehensions
    8:05 Generator pipelines
    9:49 Advanced usage, send/throw/close
    13:05 Yield from
    15:12 Thanks
  • Věda a technologie

Komentáře • 221

  • @biffenb7534
    @biffenb7534 Před rokem +393

    I love the relatively monotone presentation, which helps clarity, with only a few incredibly well placed jokes sprinkled here and there. Keep it up!

    • @Holphana
      @Holphana Před rokem +9

      Monotone? I hear many inflections.
      I would be offended at the implication towards my accent if I were in the CZcamsrs shoes. 😢

    • @biffenb7534
      @biffenb7534 Před rokem +22

      @@Holphana You’re right, I just didn’t choose my words carefully enough. What I mean is that the presentation is that of a factual text, instead of creating unnecessary clutter through adding emotion or emphasis like so many other CZcamsrs do.

    • @Ptolemarch
      @Ptolemarch Před rokem +1

      Indeed, these are vastly the best videos on coding I've found.

    • @RoamingAdhocrat
      @RoamingAdhocrat Před rokem

      What's really missing is a title card with a photo of M with chin in hands looking puzzle, or head-in-hands despairing at some topic that was exhorted in many keynote talks - TDD, say

    • @NewLondonMarshall
      @NewLondonMarshall Před měsícem

      What a wholesome reply :) ​@@biffenb7534

  • @l4luchi123
    @l4luchi123 Před rokem +144

    No matter how experienced you are, in your videos there is always a new small detail you didn't know about. Love it!

    • @georgplaz
      @georgplaz Před rokem +6

      yes! I thought "oh. I know everything about yielding.."
      and then.. bi-directional?! 🤯

  • @adsfwef1331
    @adsfwef1331 Před rokem +47

    Dude, you are a genius. I wonder why your vids aren't getting more views than those other millions of python hacks out there. Keep up the good work.

  • @SwissTHX11384EB
    @SwissTHX11384EB Před rokem +137

    Mate, I have years of Python experience, yet everytime you release a video I am floored by some of the stuff you showcase and I feel like I'm learning about the language for the first time. Stellar job, as always, and your presentation style is excellent for the job.

    • @luiz8755
      @luiz8755 Před rokem

      same
      it's a little bit overwhelming lol

  • @dhravya
    @dhravya Před rokem +52

    Always struggled with generators. Thanks for the amazing explanation!

  • @Gamecrazy721
    @Gamecrazy721 Před rokem +23

    Very insightful video! One other place I've seen generators used frequently is for API pagination. If, for instance, if you want to get all 100 records from an API, and the API limits your query to 10 records per call, you may not want to wait for all 10 calls. Instead you create a generator that calls the API only when you've completed working with the first page and are ready to move onto the second, etc.

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 Před rokem +4

      Database queries is a good example. A very common sequence is
      * Create a cursor object
      * Execute a query on the cursor
      * Iterate over the results returned from the cursor
      * Close the cursor.
      You can wrap all these steps up in a single generator function, which takes the query and lets you iterate over the results in a single step.

  • @ssholum
    @ssholum Před rokem +90

    Async (vs threading vs "other kinda-multitasking methods") video would be greatly appreciated. It's not the most useful stuff for your average script or simple program, so I rarely see good explanations of it for any language.

  • @Fikerus2
    @Fikerus2 Před rokem +23

    I write things like "sum(x for x in range(10))" very often and I didn't know that was generator comprehension! I was thinking it was the same as writing "sum([x for x in range(10)])" (with brackets). Thanks a lot for your content!

    • @yazanalhariri3700
      @yazanalhariri3700 Před rokem +1

      Me too!

    • @enkryp
      @enkryp Před rokem +4

      Why using a comprehension at all? Can't we just do sum(range(10)) ?

    • @MrRyanroberson1
      @MrRyanroberson1 Před rokem +1

      @@enkryp i was just about to mention! yeah range is directly iterable

    • @lawrencedoliveiro9104
      @lawrencedoliveiro9104 Před rokem +1

      That’s the difference between an “iterator” and an “iterable”. An “iterable” has an ‗‗iter‗‗ method, which returns an iterator when it is called. The iterator is what returns the elements of the sequence, until it is exhausted and can’t be called again.
      Because range() is an iterable, you can reuse a single range object to return any number of iterators over that range.

    • @Geza_Molnar_
      @Geza_Molnar_ Před rokem

      @@lawrencedoliveiro9104 Yeah, your explanation helps me a lot.

  • @LettuceAttack176
    @LettuceAttack176 Před rokem +14

    I swear every time I start watching a video on this channel I think “ah here is another thing I already know in python I probably won’t learn anything new this topic is pretty straight forward” and I end the video feeling like I never knew anything about it to begin with 😂😂 keep up the great work

  • @mabml
    @mabml Před rokem +34

    Your async explanation would be much appreciated! :)

  • @GlutesEnjoyer
    @GlutesEnjoyer Před rokem +3

    “Even if a file is gigabytes large you’ll only need enough memory to handle a single line” great point!

  • @vincentperrollaz5261
    @vincentperrollaz5261 Před rokem +16

    Outstanding video as always.
    itertools might have deserved a mention since it is very useful with generators.
    The jump from iterator to coroutine was a bit steep and I would personally love an async video

  • @ahmadhesham1389
    @ahmadhesham1389 Před rokem +4

    This is why I like your channel: Even when I think I know a topic well, I still expect to find something new in your videos, and I always do. Keep it up!

  • @69k_gold
    @69k_gold Před 11 měsíci +2

    Thank you! By learning this I was able to create a toy version of the async coroutines, helped me a lot to grasp the concept of event loops

  • @rituchandra6325
    @rituchandra6325 Před rokem +4

    "Where the only limit, is your imagination... and your download speed" - LOL I lost it here

  • @lex_darlog_fun
    @lex_darlog_fun Před rokem +5

    Just as I was about to suggest a video on async, James announced it himself. 👍🏻
    Can't wait to see this convoluted topic explained in mCoding simple comprehensible manner.

  • @MessLeadingProgramming
    @MessLeadingProgramming Před rokem +14

    Great video. It was eye opening for me when I learnt about generator comprehension. I realised that I was doing something very inefficient passing list comprehensions to sum and other functions.
    Also worker example is amazing. Never used it this way.

  • @wojasek1223
    @wojasek1223 Před 3 měsíci

    Thank you so much for this video, and all of others. I've started reading Fluent Python a couple months ago, but that was quite hard for me to go through it. And you on your channel describe those hard for me things and I finally get them somehow. Thought I was dumb, but all i needed was to find a great lecturer. Thank you so much!

  • @modest_supreme
    @modest_supreme Před rokem

    Thank you for this! Excellent deep dives. Your videos are a great source for understanding the why/how behind functionality.

  • @jewpcabra666
    @jewpcabra666 Před rokem +2

    always love the videos - would love an async video! Always learn a little tidbit from these

  • @pa1nk1ller14
    @pa1nk1ller14 Před rokem +1

    Your videos are going into great depth mate! Im awaiting for that async vid of yours

  • @TylerLarson
    @TylerLarson Před rokem +8

    Yep, definitely interested in an async video. Especially interested in learning the "python native" async features and components so as to detangle it from all the third-party contributed stuff.

  • @andrewstribling4385
    @andrewstribling4385 Před 5 měsíci

    Nice work! I cannot wait to start using these generator techniques!

  • @redon638
    @redon638 Před rokem

    Thanks! I always learn something new and really impressive watching your videos. Wish you twice as much subs

  • @technowey
    @technowey Před rokem +1

    Thank you for another great video.
    I’ve been using generators for years, and still didn’t know some of this.

  • @murphygreen8484
    @murphygreen8484 Před rokem +1

    Made me realize how much I still need to learn. Great video!

  • @trag1czny
    @trag1czny Před rokem +7

    craving for the async vid 🤤

  • @MoritzWallis
    @MoritzWallis Před rokem +2

    Super informative video, thank you, very interesting

  • @FlorianLinscheid
    @FlorianLinscheid Před rokem +1

    Didn't know about generator chaining, that sounded very useful! Thanks

  • @vidlb
    @vidlb Před rokem +2

    Thank you ! And yes for the async video

  • @yxh
    @yxh Před rokem +1

    I would def like a video going deeper into "yield from" generator uses, with examples

  • @ashishjain518
    @ashishjain518 Před rokem

    I probably only got 20% of this video. But it was enough for me to fiddle around and learn more about generators' daily use cases to improve my performance...
    Great video, Mcoding 😄

  • @LastTigerEyes
    @LastTigerEyes Před rokem +2

    I really appreciate your videos. I always learn something new, even when I don't think I will. TIL parenthesis make generator comprehension. :)

  • @mistervallus185
    @mistervallus185 Před rokem

    literally just had to learn about generators 2 days ago for a proj. the video timing is immaculate

  • @vt2788
    @vt2788 Před rokem

    Really advanced high value stuff! Thanks!

  • @ren200758
    @ren200758 Před rokem

    didn't know about the generator pipeline and was blown away by it. big hype for the async video!

  • @CrYpt001
    @CrYpt001 Před rokem +1

    Finally something about generators. Never quite got them

  • @dmdeemer
    @dmdeemer Před rokem +2

    Watched this video because I'm like, "I know what generators are, but I bet I'll learn something new about them." Found out that yield is an expression. Mind blown. Not disappointed.
    Please make the async video.

  • @dixonstroi
    @dixonstroi Před rokem

    I think this will really help me with lazy execution via generators. This would have really helped if . Also, 'yield from' was hard for me to get from just the docs, so thanks for summing that up tidily.

  • @macedmondson782
    @macedmondson782 Před rokem

    I'm really liking your videos! I would love to see an async video from you!

  • @krimsonsun10
    @krimsonsun10 Před rokem

    ALL hail @mcoding High Priest of the Python temple!! Your explanations are succinct, and the usage examples help me so much to grasp the concepts. Thank you.

  • @DebashishGhoshOfficial

    "Thank you, next" was a nice touch.

  • @AByteofCode
    @AByteofCode Před rokem +1

    Very nice CTA at the end, hadn't noticed it before, clever :)
    Otherwise great video and can't wait to know how async uses generators, I've been curious about that ever since you mentioned it a while ago.

  • @mattlau04
    @mattlau04 Před rokem

    Great video as always! And would love to see a video on async

  • @Cookie-mv2hg
    @Cookie-mv2hg Před rokem +2

    Every coding courses of yours it like math classes where you start at 1+1 and a simple zone out and suddenly you're on advanced mathematics.

  • @blacky7801
    @blacky7801 Před rokem +2

    You can pass things into a generator? Wow, incredible video!

  • @jullien191
    @jullien191 Před rokem

    Muy buen video. Gracias amigo

  • @endoflevelboss
    @endoflevelboss Před rokem

    Looking forward to the async video 👍🥳

  • @StrangeArrow
    @StrangeArrow Před rokem

    Super Content. Thanks for sharing with us 🥰🥰

  • @mayank8387
    @mayank8387 Před rokem

    Dude you're amazing! Thanks for sharing.

  • @mytalala
    @mytalala Před rokem

    looking forward for async video, great job

  • @aditya95sriram
    @aditya95sriram Před rokem

    That generator pipeline was eye-opening! I've worked with generators plenty, but still this pipeline idea escaped me

  • @MrTyty527
    @MrTyty527 Před rokem

    I can't wait for the async video!

  • @AIRLZ6
    @AIRLZ6 Před 3 měsíci +1

    damn i need to watch this video over and over again :D. Love it!

  • @PetrSzturc
    @PetrSzturc Před rokem +1

    I watched quite few videos about async but I would still like your take as well. It is one of the more complicated/complex? parts of the language to grasp.

  • @knut-olaihelgesen3608
    @knut-olaihelgesen3608 Před rokem +1

    Thank you so much. This was a very confusing topic.

  • @AngryArmadillo
    @AngryArmadillo Před rokem

    Looking forward to the asyncio video!

  • @martinc.7424
    @martinc.7424 Před rokem

    I was just told that list comprehension where faster than for loops... now it makes sense.

  • @hotmole7621
    @hotmole7621 Před rokem +1

    when i started python, i was so proud of my prime number generator function

  • @ciCCapROSTi
    @ciCCapROSTi Před rokem

    Good stuff, I didn't know most of the advanced stuff here.

  • @adamstrejcovsky8257
    @adamstrejcovsky8257 Před rokem +1

    when I feel on top of the world with my python knowledge, I go here to restore humility :D

  • @MichalPlichta
    @MichalPlichta Před rokem

    Wow I thought I know almost everything about generators, but i was wrong! Well done!

    • @mCoding
      @mCoding  Před rokem

      There's always more to learn!

    • @Plann
      @Plann Před rokem

      Same.

  • @HonsHon
    @HonsHon Před 6 měsíci

    Helped me refactor some code and provide some memory savings! Thank you!

  • @nassehk
    @nassehk Před rokem

    Great videos pall. Please make that async video.

  • @varkenvarken
    @varkenvarken Před rokem +1

    Would it be possible to quantify the actual memory usage of the generator pipelines shown vs list based versions? Is there some debug option or memory profiler for this? [Edit]... bit of searching later, i think scalene might be an interesting option

  • @gormster
    @gormster Před rokem +1

    No, I don’t want a video on asyncio. I want a whole goddamn *series.*

    • @mCoding
      @mCoding  Před rokem +1

      Take note of how I'm methodically making videos on all the prerequisites for a deep async discussion 🙃

    • @khalilhadji6489
      @khalilhadji6489 Před rokem

      @@mCoding can't wait, i am facing some issue in one of my projects and understanding how asyncio works inside out would be very helpfull

  • @darske1
    @darske1 Před rokem

    Plot twist: The 1 Gb file you're trying to read, has only 1 line xD
    Awesome video. The send method confuses me a lot every time I see it, I don't know why lol

  • @StephenBuergler
    @StephenBuergler Před rokem

    Do you think it would be a good idea for the else clause in the for/in/else loop to be the place where the generator's returned value is made available?

  • @klaasvaak2575
    @klaasvaak2575 Před rokem

    not just imagination or/and downloadspeed but also your pride deciding what you appropriate from the interwebs or what you painstakingly program yourself in most likely a less efficient methode.

  • @cloppingemu1471
    @cloppingemu1471 Před rokem

    Look forward to an async video

  • @mjdevlog
    @mjdevlog Před rokem

    So useful, even yhough i don't understand the last half of the video. Maybe one day i will😅

  • @greasedweasel8087
    @greasedweasel8087 Před rokem +1

    Can you do a video on making __iter__ a generator vs defining a __next__? I’ve seen both in the wild, you seem preferential to the __iter__ generator, and I’ve googled to no avail. I’m mostly interested in which one is more pythonic, but I’d also like to know what you think the use cases for each are. Great videos!

  • @laurentmichel4565
    @laurentmichel4565 Před rokem

    I would enjoy a video about asyncio a lot

  • @evolagenda
    @evolagenda Před rokem

    Fantastic

  • @arcstur
    @arcstur Před rokem

    I am async awaiting for the video on async!

  • @BR-lx7py
    @BR-lx7py Před rokem

    @9:08 It's crazy that you can even have the same name for the generator comprehensions, so all of them called "nums".

  • @BR-lx7py
    @BR-lx7py Před rokem

    This video is definitely eye-opening. I thought that generators were just regular functions that you could re-enter, but I never comprehended how python calls them totally differently. Adding something like "if False: yield" to a regular function totally changes how it is called, despite those 2 lines of code being a noop.

  • @anibaldk
    @anibaldk Před rokem +1

    You cannot see this (hopefully) but I had to give a standing ovation to this one.

    • @mCoding
      @mCoding  Před rokem +2

      I saw it!

    • @anibaldk
      @anibaldk Před rokem

      @@mCoding 😱😱😱😱😱😱😱

  • @JohnFallot
    @JohnFallot Před rokem

    Let’s go Patronssss

  • @Jakub1989YTb
    @Jakub1989YTb Před 4 měsíci

    9:40 - is there a nicer way to chain the generators like this? To not repeat the "nums" etc?

  • @dane2565
    @dane2565 Před rokem

    Yes please and thank you

  • @reef2005
    @reef2005 Před 3 měsíci

    It would help if you say something about the arg NamedTuple in the MyDataPoint class and also the '_make' method that does not exist.

  • @zacharyreilly7307
    @zacharyreilly7307 Před rokem +1

    Please make an async video!! I would love it if you included best practices for incorporating async into sync func/programs
    I find most times i need something async i want to do sync stuff too or dont know how to convert it all to async

  • @abdussametturker
    @abdussametturker Před rokem

    Awesome

  • @taylorbreutzmann6034
    @taylorbreutzmann6034 Před rokem +2

    It’s crazy, being able to tell how intelligent another human is just behind a screen/video.

  • @arthurfelipe544
    @arthurfelipe544 Před rokem

    what is the use of the line x: float? i tried to search the use of the : in that line but didn't find anything

  • @kylwatson9240
    @kylwatson9240 Před 3 měsíci

    Now if only I was doing something complex enough to merit this new found tool in my python bag... One day

  • @thyllmuller4524
    @thyllmuller4524 Před rokem

    9:42 I tried that exact code and I got the "sum is inf" - any idea what might be happening? I triple checked the code, it is identical aside from the function name being different.

  • @Blubberland
    @Blubberland Před rokem

    Thumbs up.
    4:27 This might be a rather be a problem of spell-checking settings than on syntax.

  • @Thr0nSK
    @Thr0nSK Před rokem +1

    Man you killed it with the Ariana Grande 😂😂

  • @quintencabo
    @quintencabo Před rokem

    Finally!!!

  • @dmitrylitovchenko2365
    @dmitrylitovchenko2365 Před rokem +1

    In collatz generator checking for n == 1 should be at the top otherwise it behaves funny with input of 1: [4, 2, 1] :)

    • @mCoding
      @mCoding  Před rokem

      Good catch! Yes you are absolutely right.

  • @spaghettiking653
    @spaghettiking653 Před rokem +2

    4:44 what is this _make method you call? I wasn't expecting this code to run, but it still did, even though it doesn't appear you defined the method? Is this something generated by dataclass?

    • @NostraDavid2
      @NostraDavid2 Před rokem +2

      Note that MyDataPoint class is the type NamedTuple. I googled for "_make NamedTuple Python" and got some info on the function. Turns out that _make is part of the NamedTuple class.

    • @NostraDavid2
      @NostraDavid2 Před rokem +1

      Also note that's its a NamedTuple and not a data class. This just means that you have different functions that you can use. So no comparison, like you do with data classes. You CAN do it, but you'll have to implement it yourself.

    • @spaghettiking653
      @spaghettiking653 Před rokem +1

      @@NostraDavid2 I see, thanks for pointing it out. So, I'm not sure why I thought it was a dataclass, but I guess I just saw the type annotations and didn't read the top part. That makes a lott more sense, big thanks :)

  • @alexsere3061
    @alexsere3061 Před 6 měsíci

    "Did you really think they would add a new keyword just to abbreviate a for loop?"
    This is python so yes, yes I did

  • @morrispearl9981
    @morrispearl9981 Před rokem

    I am a fan of generators. I use "yield from" when the function that generates the next thing happens to be recursive. For example, I have a generator that takes a list of N things, and yields each permutation of those N things, and the underlying algorithm is recursive.

  • @yxh
    @yxh Před rokem

    So at 9:31, the `nums` on line 15 is really a 5th-level nested generator? And whenever sum() wants the next value in the top-level generator, the inner nested generators wind all the way down to the lowest level to read the file and parse it one row at a time?

  • @farpurple
    @farpurple Před rokem

    ~~I got my dose of dopamine~~
    Thanks you, but i should watch more times/try in code to understand yield and yield from returns, h, im still on way to switch to rust but python is so interesting!

  • @ObsessiveClarity
    @ObsessiveClarity Před 9 měsíci

    I find myself routinely wanting to iterate backwards through a list with access to the correct array indices:
    for i,x in reversed(enumerate(myList)): # enumerate(myList) is not reversible so this sadly doesn't work.
    ...
    for i,x in reversed(list(enumerate(myList))): #works but is moving memory around for no good reason.
    ...
    for i,x in zip(range(len(myList)-1, -1, -1), reversed(myList)): # works but is less readable / higher cognitive load
    ...
    for i,x in zip(reversed(range(len(myList))), reversed(myList)): # OK but makes me very slightly sad
    ...
    Anyone have any good tips for this?

  • @briban65
    @briban65 Před 3 měsíci

    what is NamedTuple in the file processing one??

    • @mCoding
      @mCoding  Před 3 měsíci

      I talk about it in this video! czcams.com/video/vCLetdhswMg/video.html

  • @miQize
    @miQize Před rokem

    What's the difference between yield from and just a yield followed by a send to the wrapped generator?

    • @mCoding
      @mCoding  Před rokem

      See peps.python.org/pep-0380/#formal-semantics for the formal semantics. As you can see, there are a huge number of edge cases and exceptions that it takes into account.