Asyncio - Asynchronous programming with coroutines - Intermediate Python Programming p.26

Поділитися
Вставка
  • Опубліковано 20 сер 2024
  • Welcome to an Asyncio with Python tutorial. This tutorial will be specifically for Python 3.5+, using the latest asyncio keywords. Asyncio is the standard library package with Python that aims to help you write asynchronous code by giving you an easy way to write, execute, and structure your coroutines. The Asyncio library is for concurrency, which is not to be confused with parallelism.
    Text tutorials and sample code: pythonprogramm...
    Discord: discordapp.com...
    Support the content: pythonprogramm...
    Twitter: / sentdex
    Facebook: / pythonprogramming.net
    Twitch: / sentdex
    G+: plus.google.co...

КОМЕНТАРІ • 237

  • @JohnDoe-vr4et
    @JohnDoe-vr4et 5 років тому +396

    I didn't know Edward Snowden was now doing Python tutorials.

    • @Cal97g
      @Cal97g 5 років тому +3

      I actually thought this about this guy when I first saw him a few years ago haha

    • @michaelwilson8461
      @michaelwilson8461 5 років тому +2

      Honestly, when I first started this series I couldn't help thinking he needed an "evil" white lab coat and old fashioned dark welding goggles sitting on his head.
      Thought I was watching Dr Horribles' Python blog for a second.
      Guess we know what would happen if Neil Patrick Harris(on) and that oldest kid from malcom in the middle had offspring lol

    • @thengakola6217
      @thengakola6217 3 роки тому

      u should've known

    • @catharsis222
      @catharsis222 3 роки тому

      I thought the lead singer of Semisonic

    • @shayneloyd
      @shayneloyd 3 роки тому

      Shh, if they catch on they will stop sending him the UA-cam money.

  • @vidura23
    @vidura23 4 роки тому +8

    I just completed your tutorial set during the lockdown and I just want to say a massive THANK YOU for your tutorials. I'm a mechanical stress engineer and I always wished that I knew coding to automate and write programmes to help with my work. I now have a good basic understanding of Python thanks to you and several other UA-camrs. I even managed to build few robots. Keep doing what you are doing!

  • @bradm8128
    @bradm8128 5 років тому +43

    love learning python from Mr. Snowden

  • @damianshaw8456
    @damianshaw8456 6 років тому +8

    Very helpful, I'd just got my head around starting to write Python async code and this was great.
    FYI I believe it's standard practice to do "await asyncio.sleep(0)" not "await asyncio.sleep(0.00001)". The 0 is enough to interrupt the task and give the loop/interpreter a chance to switch to something else and it saves having to create a real timer which I think can have small performance hits.

    • @sentdex
      @sentdex  6 років тому +2

      You are absolutely right about the sleep(0) being the paradigm, thank you for the clarification

  • @smartmineofficial
    @smartmineofficial 6 років тому +117

    Asyncio sounds like 'Ay, se cayó!' in Spanish, which translates to 'Oh no, he fell down!'

    • @MrTeddybearGame
      @MrTeddybearGame 5 років тому +30

      Probably the guy that tried tying his shoe while running...

  • @nano7586
    @nano7586 4 роки тому +14

    7:05 AMEN. Documentations just need to have a short introduction with a simple example so people at least know what they're dealing with. I don't understand how this isn't a thing.. seriously. People would have so much more general knowledge with such easy things (applies to Wikipedia, university, tutorials, literature, etc.)

  • @shreyashkashyap
    @shreyashkashyap 3 роки тому +1

    This was the best explanation of Coroutines on UA-cam that I found.

  • @vapon
    @vapon 6 років тому +1

    Coroutine stands for concurrent routine.
    When a function is to be split in pieces (async), then await should be called somewhere in that function and it's where the function (the flow) is going to be split (interrupt). Those interruptions and callbacks must be co-ordinated by someone: that's the event loop! A fifo queue where jobs are scheduled. So the reason of an await asynchio.sleep() is to give the function a chance to be split and the event loop a chance to check its queue of what else has to start or resume ;)

  • @_test_test
    @_test_test 2 роки тому

    for a long time i was ur subscriber but about a half a year im starting programming myself. ure doing awesome lessons, coz u show it in easy way. thx budd.

  • @williamli55
    @williamli55 Рік тому

    I was waiting forever for you to address the fact that the entire function is CPU bound. I was about to throw a tantrum in the comments. Glad I waited😁

  • @bratwurst6666
    @bratwurst6666 4 роки тому +3

    I enjoyed that he was hanging on the if-statement. It is just more realistic that shit like this goes wrong.

  • @sudiptapandit7640
    @sudiptapandit7640 6 років тому +5

    What a coincidence! I just about to search other sources for this topic... but now i can get it from my favorite source .😘

  • @Sciencedoneright
    @Sciencedoneright 3 роки тому +1

    It doesn't even seem useful but it is so useful

  • @pisoiorfan
    @pisoiorfan 5 років тому +39

    if i % 50000 is TRUE 49999 times, that's why it got so slow

    • @aslan1504
      @aslan1504 4 роки тому

      Well, it depends on i var)

    • @berndo3038
      @berndo3038 3 роки тому +2

      Actually, even more than that in his example. Because it would be truthy for anything that's NOT divisible by 50,000. Which if you're iterating through every number from 0 to 508,000 would happen 507,990 times.

  • @rivaanb
    @rivaanb 6 років тому +11

    Asynckio 😂 this is what I will call it from now on 🙌🏼 great video! Thanks..

  • @abuslume4169
    @abuslume4169 Рік тому

    Besides that bug where you forgot the == 0 after the modulo statement and i was yelling at my screen, this is the only tutorial i've watched that's been able to help me with wrapping my head around the asyncio library. Thank you!

  • @mitchellfolbe8729
    @mitchellfolbe8729 4 роки тому

    Thank you for all of these videos. Lots of fun going through them all. Appreciate the hard work.

  • @muhammadtalhabaig4908
    @muhammadtalhabaig4908 5 років тому +2

    Thanks a lot for this series man! Really enjoyed and learned a lot from you. I hope you will be making more tutorials like these in the future. My favourite part in this series was the blob game project. Keep it up 😃

  • @FuZZbaLLbee
    @FuZZbaLLbee 6 років тому +7

    Have had good experiences with await in c#, so will also try it out in Python

  • @DivineZeal
    @DivineZeal 5 років тому +1

    This is the final gem i needed for my python bot, thank you, master Sentdex aka Edward

  • @taxi_boast
    @taxi_boast 2 роки тому

    Thank you for taking the time to make this video. I must say though that the tying the shoelace example wasn't the most intuitive or appropriate. There are better examples to use.

  • @keklol1408
    @keklol1408 6 років тому +1

    Actually, it would be much more productive to take the "div_by" and multiple it by following integers until the result it is less than "inrange".
    Thank you for your tutorials, they are great.
    I understand that this function is just for a sake of example.

  • @MelarDev
    @MelarDev 5 років тому

    12:40 Yes, there are examples when you use async without await, anything you do over an unreliable protocol such as udp, for example send logs to a server or streaming media may be done asynchronously and you never want to know anything, you even skip errors so you never do await.

  • @JusticeNDOU
    @JusticeNDOU 2 місяці тому

    you cannot DOS someone if you do not await, because once you do not await you probably never even had a coroutine or you have a coroutine but its not sent to the event loop, the effect in eiher way is that you end up with an awaitable which is never executed

  • @teddycristian2779
    @teddycristian2779 4 роки тому

    thank you for the intro, you made it clear with the running example.

  • @cluberic
    @cluberic 4 роки тому +4

    At 11:40, can you explain how you are using the variable "loop" in main(), when it was declared in if __name__ == '__main__':?? Are variables instantiated in that usable in the whole class?

  • @chuckynorris616
    @chuckynorris616 6 років тому

    much easier to run parallel functions using the gather method instead of hacking with sleep and awaits
    loop.run_until_complete(asyncio.gather(
    find_divisibles(508000, 34113),
    find_divisibles(100052, 3210),
    find_divisibles(500, 3),
    ))

  • @unshakeabletraderph6971
    @unshakeabletraderph6971 2 роки тому

    The best way to visualize async is when Jackie Chan fights multiple opponents. 🤣😂

  • @77shoemanable
    @77shoemanable 3 роки тому

    Best explanation ever !!

  • @i701Dev
    @i701Dev 3 роки тому

    Thank you for this tutorial.

  • @kunomels
    @kunomels 6 років тому

    Very nice video thank you :) (Some sound engineer advice : put a high-pass filter at about 100Hz on your mic feed. It makes it more confortable to listen by eliminating low freq shocks)

  • @oliverwann3300
    @oliverwann3300 5 років тому

    Thanks a lot for your giving. I am a 'asyncio' beginner. AND I think ..emm... I should spend some time to learn it .

  • @tylerhuang6701
    @tylerhuang6701 2 роки тому +1

    Great video! I have a question about the output at 20:12. If I understand it correctly, divs2's task finishes before divs3's task because in divs2's task, i never reaches 500,000 so it never hits sleep(). So then I was wondering why it prints out "finding sums in range 500 divisible by 3" before printing out "Done w/ nums in range 100052 divisible by 3210" because shouldn't divs2's task finish before div3's task starts as it was never put to sleep?

  • @Astral96
    @Astral96 5 років тому +3

    @2:10 "and waiting on a response" * starts drinking * and we be waiting hahaha

  • @Scratchmex
    @Scratchmex 6 років тому

    You can use asynio.sleep(0) to just gives back control and not have time penalty for each change

  • @somethingcoolgoeshere
    @somethingcoolgoeshere 5 років тому +5

    "unless your trying too dos somebody" lol good example

  • @carolchen4753
    @carolchen4753 4 роки тому +1

    Very helpful. Thanks Edward!

  • @tuhinmukherjee8141
    @tuhinmukherjee8141 3 роки тому

    Hey good work Harrison, but for people who are really interested in going into the details, you might wanna check out EdgeDB's "import asyncio" series which is by far the best asyncio series I've ever seen. Asyncio is TOO huge to be covered in a single 30 minutes video !

  • @vuminhquanle1426
    @vuminhquanle1426 4 роки тому

    10:20 LoL, I laughed so hard when you try to negotiate with the language about how it should be

  • @gesuchter
    @gesuchter 6 років тому +2

    It's been a long time since the last video in this series :o I love them, please post them more often!:)

    • @sentdex
      @sentdex  6 років тому +2

      any requests for fitting topics to this one?

    • @max2070
      @max2070 6 років тому

      maybe new Django/Flask or AI project will be good?

    • @lucagorzog2490
      @lucagorzog2490 6 років тому

      sentdex dataclasses ? type notation?

    • @randiaz95
      @randiaz95 6 років тому +2

      I think one thing I would really like to learn is encrypting in python.

    • @Boxylon
      @Boxylon 4 роки тому +1

      @@sentdex hashing and hash tables

  • @el3ctron
    @el3ctron 4 роки тому

    thanks for sharing NSA secrets and doing this python tutorials

    • @sentdex
      @sentdex  4 роки тому +1

      My pleasure!

  • @asifmohammed5436
    @asifmohammed5436 3 роки тому

    16:50, check reminder is 0, otherwise program will stop for 0.00001 * (~100000) seonds

  • @edwardwilliamsams6589
    @edwardwilliamsams6589 6 років тому

    thanks for all the hard work Sentdex.

  • @wuda-io
    @wuda-io 6 років тому +22

    When you like sublime... then try vscode i went from idle to sublime to vscode its awesome :D

    • @ego_sum_liberi
      @ego_sum_liberi 6 років тому +2

      Yes, vscode is top!

    • @Alex4n3r
      @Alex4n3r 6 років тому

      It's very scary that the new IDEs are built in html and therefore are vulnerable to html injection (even as comments) when you run downloaded code.

    • @ChEkOv
      @ChEkOv 6 років тому +2

      I was in notepad++, then vscode then sublime.. now I recommend atom! community first.

    • @VictorRodriguez-zp2do
      @VictorRodriguez-zp2do 6 років тому +3

      Vim is always better

    • @vapon
      @vapon 6 років тому

      sublime is c++ and python

  • @pawsdev
    @pawsdev 5 років тому

    So, after this tutorial i understood, that yet nobody knows how to cook async properly and why it is invented

    • @sentdex
      @sentdex  5 років тому

      Apparently you realized that about yourself.

  • @uppubhai
    @uppubhai 6 років тому +1

    Much needed video, Thanks a lot sir

  • @tankman6452
    @tankman6452 5 років тому +1

    I try it again and again, the sample code just doesn't work, the amount time is always same whether use asyncio or not.

    • @tankman6452
      @tankman6452 5 років тому +1

      Oh, I know why! First time you finished in 32.6s because range number is 50800000, and second time you finish in 0.4s, it's not because you use asyncio, you just modify range number to 508000 and edit the video. You think all users are idiots? no idea where these good comments come from. full of bullshit

    • @dan400919
      @dan400919 4 роки тому

      @@tankman6452 it is not about accelerate execution of div1, it is about to not wait till prev instruction is executed. it doesn;t matter if you put 50800000 or 508000, in both you have to wait till div1 is executed which it takes almost 30 sec , so you are somehow blocked by div1 to have result for div2. using async you get div2 results till div1 is processed. He did a presentation mistake , though.

  • @Indemere
    @Indemere 6 років тому

    Yo sentdex, you should do a tutorial on Apache Spark, from processing huge data sets! Would be very interesting to see your take on it. Cheers man, love the videos!

  • @tomaszsosinski5935
    @tomaszsosinski5935 6 років тому

    Hi! I liked the video a lot! Great work! I only wanted to point out that concurrency and asynchronous computations are two different things and it is a bit dangerous to use them interchangebly.

  • @fastrunner8494
    @fastrunner8494 3 роки тому

    Man i learned you are very happy.

  • @sundaresann4749
    @sundaresann4749 6 років тому

    Please make a video on how you make your videos , I mean how do you learn , practice, take notes to teach ?? Will you be using any tools I'm sure u do . What is it? How do actually you manage time BY making THIS MUCH OF VALUEABLE CONTENTS ?? im curious as well as confused. Shd I ve to take teaching notes while learning or during practice . If you have time please make a video. Will be useful for many. Thank you a lot.

  • @soundwaves1752
    @soundwaves1752 2 роки тому

    probably I don't understand concurrency, but your first example was a cpu bound task. why should you use asyncio on that.
    why should the task give control back to the loop when it is cpu bound.
    i think multiprocessing would do better for that and not asyncio.

  • @PlasmoX
    @PlasmoX 4 роки тому +2

    when running async on a function, does that mean i need to make all other functions run async? or just what i want to run together?

  • @skndash96
    @skndash96 3 роки тому

    located = [i for i in range(inrange) if i % div_buy == 0] easier!

  • @rifatmasud
    @rifatmasud 4 роки тому

    You're just one happy programmer 😀

  • @bottlerider8898
    @bottlerider8898 5 років тому

    If asyncio.get_event_loop() fails for some reason, you'll try to execute a method of a non-existent object in the finally section.

  • @wilfreddv
    @wilfreddv 6 років тому

    I think `run_until_complete` waits for a return value from `main()`. `main()` just creates a couple of tasks and returns `None`, not awaiting the tasks.

  • @EnglishRain
    @EnglishRain 4 роки тому

    Amazing video! Thank you so much Ed!

  • @PelicanRefractaire
    @PelicanRefractaire 4 роки тому +4

    Everybody is talking about Snowden but I actually see Aaron Paul trying to sell blue meth online

  • @padraic1983
    @padraic1983 2 роки тому

    Damn SentDex.. just saw you broke 1 million!

  • @europmedia4828
    @europmedia4828 3 роки тому

    Thank You!

  • @josephs3973
    @josephs3973 5 років тому

    Just starting out with Python. How come the loop object is in scope in main()? Is it magically passed by run_until_complete() or something like that? Ugh.

  • @Rostgnom
    @Rostgnom 6 років тому +6

    Why isn't `loop` undefined in main()?

    • @ZenMasterScr3wy
      @ZenMasterScr3wy 6 років тому +2

      Loop is defined before main() is called.
      loop = asyncio.get_event_loop()
      loop.run_until_complete(main())

    • @Rostgnom
      @Rostgnom 6 років тому

      Oh, right, now I see it. That's why you should follow programming practices tbh ^^

  • @adriantarver2229
    @adriantarver2229 6 років тому +1

    Hey sentdex, have you ever thought about covering the cryptography module for python 3.6? I was wondering if you could possibly cover it at some point?

  • @Tweakimp
    @Tweakimp 6 років тому +2

    Is there a reason why you use "... {}...{}...".format(x,y) and not f"... {x}...{y}..."? The second is so much easier to read.

    • @cizbarca
      @cizbarca 6 років тому

      Franz W backwards compatibility

  • @raghav4296
    @raghav4296 4 роки тому

    Came here after your Go routines tutorial. Thanks for all the explanations and knowledge. Appreciate it.
    Asyncio is not supported in Flask and I guess Django has limited support. Rest async libraries like Sanic /aiohttp has limited to no cloud API examples.
    As a python backend person working on any of the public clouds, how would one send async requests as easy as we do in NodeJS..?
    Thank you.

  • @bokunochannel84207
    @bokunochannel84207 2 роки тому

    dead by lock? nah dead by await! good!

  • @samapriya1
    @samapriya1 6 років тому

    Is it possible to show an example with an asyncio downloder downloading maybe from a list or urls? Would love to have that application built using async instread of multiprocessing

  • @rammanoj6110
    @rammanoj6110 5 років тому

    hey, thanks for the tutorial. But I guess using running the same code locally increased the time (instead of decreasing) on adding the condition `if i % 5000 == 0: await asyncio.sleep(0.0001)`. The one thing I don't understand is even if you perform blocking, it just stops the current loop and executes another. However, it has to perform all the computations. So, you are not blocking the coroutine while it is waiting, you are doing while the computation is equal to some number. So it need to perform the computation again once it resumes. Hence I don't find the need of above if statement?

  • @EriksonRodriguez
    @EriksonRodriguez 4 роки тому

    Thanks

  • @J2000Ray
    @J2000Ray 3 роки тому

    Could someone tell me how the references to that loop object in his main function are valid? That loop object shouldnt be in scope of that main function, right?

  • @DarkRedman31
    @DarkRedman31 5 років тому

    I like the video, but still after I watched it, I don't get the point of asyncio in this example, and sync coroutines can already be done using generators (cf works and examples done by David Beazley aka Dabeaz), why asyncio ?

  • @infiltr80r
    @infiltr80r 4 роки тому

    The world famous Ecuadorian fly fisherman Asyncio Gonzalez.

  • @hamrozjumaev
    @hamrozjumaev 6 років тому

    Hi Sentdex
    Firstly I wanna thank you for all this amazing video tutorials that you are sharing with us. Secondly I request you to assist me with my problem which I faced on django tutorial on lecture 5, I already commented the issue there but did not get answer.
    I hope that you will once look at it
    Thank you an advance

  • @MElixirDNB
    @MElixirDNB 3 роки тому

    how is loop defined in main? Is there some magic happening in asyncio that makes the loop variable available because you call loop.run_until_complete ?

  • @paddym27
    @paddym27 5 років тому

    great video, thanks!

  • @NaturalBornCamper
    @NaturalBornCamper 3 роки тому

    I usually understand everything after Sentdex's videos but this time I'm so lost and confused. I don't understand the role of "await"

  • @NewsSphereNetwork
    @NewsSphereNetwork 2 роки тому

    HaHaHa the most replayed part is when you find the error, that modulus error happens to me every time, thanks god it is not only me hhh

  • @prhmma
    @prhmma 3 роки тому

    can anyone please tell me the name of this theme?

  • @lostlewis7577
    @lostlewis7577 5 років тому

    Have you heard of, or use, uvloop in unison with asyncio to replace event loops? Went snooping around and it seems like it might be a good drop in library. Thoughts anyone?

  • @ravishankar2180
    @ravishankar2180 6 років тому

    use ublock origin for ad blocking in your browser. It's powerful.

  • @punyamaremalla2444
    @punyamaremalla2444 4 роки тому

    what is add_done_callback ?

  • @wolfisraging
    @wolfisraging 6 років тому

    Thank u so much sir, just keep doing what you do.
    Big fan😊

  • @bingog8900
    @bingog8900 6 років тому

    thank you for sharing

  • @simzhou
    @simzhou 4 роки тому

    Hi @sentdex really thanks for your video on this and I think your's is the most clear one among all!
    Could you maybe make a new video and explain more on callback functions for us?:) Since instead of using asyncio.wait(), I found it common to use sth like "asyncio.call_soon()" or "asyncio.call_later()" in others' codes, and I think it is kinda confusing to understand...Thanks a lot!

  • @yugandharchaudhari1376
    @yugandharchaudhari1376 5 років тому

    should a caller f2 of async function f1 should necessarily async?

  • @Xaminn
    @Xaminn 3 роки тому

    Lmao. Literally the last video I watched I was like "aysinko"? LOL. Then I hear you say other people will judge. I'm like, well.... Shit....

  • @y031962
    @y031962 3 роки тому

    if statement should be "if i%50000 == 0:" then you want to wait

  • @sparttann1312
    @sparttann1312 6 років тому

    I'm working in Spyder(+ Ubuntu) and get RuntimeWarning: coroutine 'main' was never awaited with final script from pythonprogramming page. Any idea?

  • @trykozmaksym
    @trykozmaksym 4 роки тому

    Good stuff.

  • @IsItTimeToTravel
    @IsItTimeToTravel 6 років тому

    Great job. A question. Where can we use this ? If I have a web page with many objects that I am refreshing every minute (assume), can I use asyncio to achieve independent updating without reloading?

  • @nikhilnambiar7160
    @nikhilnambiar7160 5 років тому

    Can we use async to read more than 10k files and perform operation over it ?

  • @DaLoler1
    @DaLoler1 6 років тому +1

    The fact that i see him use sublime amazes me

    • @sentdex
      @sentdex  6 років тому +6

      I even paid for a license a while back! It's official!

    • @Vinomix
      @Vinomix 6 років тому +1

      Yoo rock bro, i am also a sublime guy.

  • @marcelnitan
    @marcelnitan 5 років тому

    Is there any difference between using create_task(func()) and await func() ? Like I'm used of doing
    async def main():
    var1 = await func()
    instead of
    async def main():
    var1 = loop.create_task(func())
    await asyncio.wait(var1)

  • @NagarajCruze
    @NagarajCruze 4 роки тому

    How can we use this program without making it to sleep?

  • @enriquematos6461
    @enriquematos6461 6 років тому

    hi man, great video but I have struggled a lot installing the package asyncio... do you have any guide? the usual pip does not work

  • @ChEkOv
    @ChEkOv 6 років тому

    Please describe diff between asyncio vs multiprocessing with some example pls.
    thanks!

    • @sentdex
      @sentdex  6 років тому +1

      multiprocessing can still be highly wasteful with latency and i/o times. You might be able to get jobs done in similar times, its just the asyncio will do it more efficiently in terms of hardware used. That said, you can combine the two, and ideally would. They just aim to solve different problems. Multiprocessing just helps you fully utilize the hardware that's available to you. Asyncio helps you fully utilize your time. Hope that helps.

    • @ChEkOv
      @ChEkOv 6 років тому

      Excellent. As we're getting used to :)

  • @Vinomix
    @Vinomix 6 років тому

    Quick question why did you pick sublime text over the other editors. Please Answer ..!!!! Thanks

  • @omarsalama6312
    @omarsalama6312 6 років тому

    can you add to GtA5 play the v6 to tutorial with data and code ? or add it on github

  • @nektoxyz1013
    @nektoxyz1013 6 років тому

    Hi. Maybe i'm wrong, but..
    should i explicitly set await.sleep(n) period?? n goes to infinite lower, i suppose.
    or..
    await asyncio.sleep(0)
    expression for returning CPU timing for another coroutine. another coroutine takes CPU time intil it stops execution, or meets same expression.
    or I got that logic wrong??
    P.S. Thanks for tutorial on asyncio. I;ve spent a lot of time trying my code run asynchronosly)) But till now i'm not sure if it is runs so...
    Waiting for another video about asyncio, aiohttp, or websockets pytohn lib (they are written in async), or anything with async.
    For me it looks like async Magic))