Python Asynchronous Programming - AsyncIO & Async/Await

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024
  • In today's video, I'll be talking to you about asynchronous programming in python. This Python Async tutorial will cover the 'async' and 'await' keyword, coroutines, futures and tasks, and some basic features from the asyncio module in Python. This video is for intermediate programmers, and it's recommended you have Python 3.7 or above.
    💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code "techwithtim" algoexpert.io/...
    📄 Documentation
    AsyncIO: docs.python.or...
    ⭐️ Timestamps ⭐️
    01:43 - Synchronous vs Asynchronous
    04:30 - Coroutines
    07:35 - Async Event-Loop
    08:58 - Async/Await Keywords
    12:12 - Tasks
    17:00 - Async Example
    ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
    💰 Courses & Merch 💰
    💻 The Fundamentals of Programming w/ Python: tech-with-tim....
    👕 Merchandise: teespring.com/...
    🔗 Social Medias 🔗
    📸 Instagram: / tech_with_tim
    📱 Twitter: / techwithtimm
    ⭐ Discord: / discord
    📝 LinkedIn: / tim-ruscica-82631b179
    🌎 Website: techwithtim.net
    📂 GitHub: github.com/tec...
    🔊 Podcast: anchor.fm/tech...
    🎬 My RUclips Gear 🎬
    🎥 Main Camera (EOS Canon 90D): amzn.to/3cY23y9
    🎥 Secondary Camera (Panasonic Lumix G7): amzn.to/3fl2iEV
    📹 Main Lens (EFS 24mm f/2.8): amzn.to/2Yuol5r
    🕹 Tripod: amzn.to/3hpSprv
    🎤 Main Microphone (Rode NT1): amzn.to/2HrZxXc
    🎤 Secondary Microphone (Synco Wireless Lapel System): amzn.to/3e07Swl
    🎤 Third Microphone (Rode NTG4+): amzn.to/3oi0v8Z
    ☀️ Lights: amzn.to/2ApeiXr
    ⌨ Keyboard (Daskeyboard 4Q): amzn.to/2YpN5vm
    🖱 Mouse (Logitech MX Master): amzn.to/2HsmRDN
    📸 Webcam (Logitech 1080p Pro): amzn.to/2B2IXcQ
    📢 Speaker (Beats Pill): amzn.to/2XYc5ef
    🎧 Headphones (Bose Quiet Comfort 35): amzn.to/2MWbl3e
    🌞 Lamp (BenQ E-reading Lamp): amzn.to/3e0UCr8
    🌞 Secondary Lamp (BenQ Screenbar Plus): amzn.to/30Dtafi
    💻 Monitor (BenQ EX2780Q): amzn.to/2HsmUPZ
    💻 Monitor (LG Ultrawide 34WN750): amzn.to/3dSD7tS
    🎙 Mic Boom Arm (Rode PSA 1): amzn.to/30EZw9m
    🎚 Audio Interface (Focusrite Scarlet 4i4): amzn.to/2TjXsih
    💸 Donations 💸
    💵 One-Time Donations: www.paypal.com...
    💰 Patreon: / techwithtim
    ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
    ⭐️ Tags ⭐️
    - Asynchronous programming
    - Coroutines
    - Futures in Python
    - Tasks in Python
    - Python tutorial
    - Tech With Tim
    ⭐️ Hashtags ⭐️
    #Programming #Asynchronous #TechWithTim

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

  • @PeterJacobFloratos
    @PeterJacobFloratos Год назад +12

    A quick story. I started programming 4 years ago at Tim was the first instructor in this vast sea of programming. When I learned the basic I kinda move on and start my own journey. Today in my work I need to use asynchronous programming and of course I knew the place to learn. Tim you are amazing, thank you so much for the knowledge you have given us!

  • @yoyoteo99
    @yoyoteo99 3 года назад +343

    "a programmer had a problem and he thought to solve it with thread.
    has problems. two Now he"

  • @TheKiryu.
    @TheKiryu. 3 года назад +459

    It would be great to learn about the differences between acyncio, multiprocessing and threading

    • @JoshelinRico
      @JoshelinRico 3 года назад +64

      asyncio and threading are almost identical, but threading is more intuitive. They are mainly used for I/O bound tasks.
      Mulltiprocessing is very different. It bypasses the GIL (look it up if you don't know what it is). It is mainly used to improve performance with parallel programming.

    • @sleepymarauder4178
      @sleepymarauder4178 3 года назад +54

      Both asyncio and threading are concurrent.
      Threading is being handled by the OS and AsyncIO is being handled within python ( the async event loop ).
      Threads can execute small operations to speeds things up ( e.g. adding more robots to handle the work, difficult to oversee and manage when program grows big. Also race conditions where: comes out weird the outcome )
      asyncio is done by using an event loop where task are being awaited ( e.g. non-blocking! tasks that are fired up and deliver some result while the program is doing other things )
      At the end of the event loop ( yes it is a loop, all the results are gathered from the loop and it starts over again )
      If tasks are blocking, asyncio isn't the right tool at all. Luckily you can also "throw" blocking tasks into a different executor so that they dont slow down your async stuff.
      Multiprocessing is using multiple processes to do the grunt work. It kind of bypasses the GIL by having more processes with another GIL.
      Drawback can be copied memory and such.
      Basically every technique has an advantage and a drawback. I do like asyncio because it is a simple solution to a complex problem.
      The thing is that when using an Executor you can test different scenario's within Python because you can swap out multiprocessing, threading and asyncio easily.
      Test and see what does what.

    • @sadhlife
      @sadhlife 3 года назад +14

      @@sleepymarauder4178 thank you.
      i see so many people spreading knowledge about threading vs. async which is wrong. good to see at least there's people out there explaining things completely and correctly.

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

      Threading and multiprocessing are preemptive, coroutines are not. Coroutines and threading are default-share-everything, multiprocessing is default-share-nothing. Coroutines are easier to debug than threads.

    • @imnormal-sl8mj
      @imnormal-sl8mj 3 года назад +1

      ​@@sleepymarauder4178 do you know when is it better to use threading over async?

  • @enamulmajid8424
    @enamulmajid8424 3 года назад +13

    Just started with asynchronous programming in python, and this video of yours helps me to get comfortable with the asynchronous concept.
    Thank you @tim
    (well, I must include, I have a good grasp in the primary concepts of python, then I headed to the asynchronous concept in python)

    • @razslin238
      @razslin238 7 месяцев назад

      😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊

    • @razslin238
      @razslin238 7 месяцев назад

      😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊😊

  • @future9715
    @future9715 3 года назад +55

    asyncio is pretty useful when you're coding server's responses etc. While one request is being processed, the other one begins.

    • @SA-oj3bo
      @SA-oj3bo 3 года назад +1

      Hi do you know maybe some good tutorials how to use asyncio to handle multiple tcp sockets on a server? What would be the advantage to handle multiple sockets with asyncio compared to handle multiple server sockets with threads?

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

      Can you compare the asyncio vs thread pool executor for me. I'm creating a script about sending and receving the request but when using TPE, the thread is locked for no reason

  • @kitetm7596
    @kitetm7596 3 года назад +30

    I wanted this for so long thank you so much! :)

  • @krause3d
    @krause3d 3 года назад +6

    Great stuff! I've been reading up on this for a few days now and your breakdown has been the clearest explanation. Thank you.

  • @nogamenolife9182
    @nogamenolife9182 3 года назад +1

    Oh, man. I needed this. I watched lots of videos but none of them were as good and simple-explained as yours.

  • @angelcaru
    @angelcaru 3 года назад +12

    This was suggested by Dovid S. on this same video, but I would really like a series where you go through the code of popular Python packages and/or modules .

  • @carewen3969
    @carewen3969 3 года назад

    I'm about a month into learning Python. That was a great explanation and gives me a foundation to dig deeper. It shows me how I can have multiple things happening at the same time, and the concept of futures really is exciting; in that I can see how the idea in my mind can actually be built.

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

    I learned asynchronous programming on hard mode, means that when I started my first asyncio project (discord bot) I knew nothing about it, and barely a beginner in programming world and python In general i struggled days even for simple stuff, though this made me really learn not just scrolling through videos and remember nothing after over one year of working at my project ( which is alive even now, because I'm always performing maintenance checks on my bot) I still feel like I have a lot to learn even if I'm able to write a generous amount of code without "cheating" (searching for answers or something)
    Great video for people who want to dive more deeper about asynchronous code

  • @imherovirat
    @imherovirat 3 года назад +6

    Man what the actual F, I was learning to make discord bot and now I get this video, you must be reading my head, Thanks man learning a new topic fromfav youtuber is really Awesome!

  • @99ansh
    @99ansh 2 года назад +1

    One of the best videos to get started with asyncio!

  • @sachinsinghal13
    @sachinsinghal13 3 года назад +10

    Thanks Tim, this was a really helpful and useful and awesome tutorial, I really enjoyed it. I 'await' fot the next tutorial!!!

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

    This is an absolutely spendid demonstration of asyncio, I needed to use it today and had no clue how to go about it, now I'm off to testing my understanding on my product. Thanks Tim.

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

    As always a great video!
    There is just one point that was missing for me (a python-noob):
    Global variables are shared between the async routines, so it looks to me like is multithreading and not multitasking - that makes it even better!

  • @jenex5608
    @jenex5608 3 года назад +5

    Before i was confused with threading and async. Thanks to tim, i now see the difference between threading and async. Threading suspends the thread/task, and runs the other thread, whereas, asycnio doesnt suspend anything it just gives execution

  • @superthaix
    @superthaix 7 месяцев назад

    Absolutely fantastic and best video explanation of the asyncio and the keywords. Actually , very clear and to the point and thanks for not using ridiculous analogies.

  • @lawrencedoliveiro9104
    @lawrencedoliveiro9104 3 года назад +4

    12:58 There is a chance that could fail. asyncio only holds weak references to the tasks it creates; it relies on the caller (you) to maintain strong references, to stop those tasks from disappearing randomly. Here it executes after the “task” variable holding the reference has gone.

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

    Thanks man, I have toi say one of the best tutorial over the whole asyncio python package ;)

  • @RafaelGuedes84
    @RafaelGuedes84 2 года назад +2

    Hi Tim, thanks a bunch for this video. I was struggling to understand asyncio and you made it simple to grasp. God bless you!

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

    This was a good video to get a basic understanding of it but not full enough to actually know what applications to use it for. It reminded me of threads or background jobs.

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

    Awesome!! Was waiting for this from soo long

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

    This is the first time I really understood the basic mechanics of asyncio. Thank you!

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

    Best explanation on RUclips. Thanks TIM !!

  • @MandolinSashaank
    @MandolinSashaank 3 года назад

    Man you make things so simple. Why are you not famous yet! Thank you so much for this! :D

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

    thanks bro.... shortest tutorial with the most beneficial concept!

  • @m.jamilrahman4971
    @m.jamilrahman4971 Год назад

    Since I found out that Python supports asyncio, I always avoid it, I prefer multi threading. But thanks to this tutorial I will start my project using asyncio. Multi threading feat asyncio is the best duet. Great Job Tim, greeting from Indonesia 🍻

  • @marctorsoc8309
    @marctorsoc8309 3 года назад

    this is the 5th video I watched today about asyncio and finally got it. Thanks for this, it was really clear :)

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

    Finally, someone explained this so I could understand. Liked, subscribed 👍

  • @therzook
    @therzook 3 года назад +1

    Here we go another video from 'not a prodigy' kid! Boy I am 39 and you are my idol and inspiration, finally after 20 yrs of lingering with coding - you taught me something productive ;) Keep doing this great job. Thanks.
    After 6 months I actually could apply some of Python in electrical engineering (electrical!). Soon my paperwork will be gone...

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

    i would just say "PERFECT" for this explanation .
    Thanks Tim !!

  • @lesmonsaluta
    @lesmonsaluta 8 месяцев назад

    Really great video! One of the best ways of explaining I have seen.

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

    I paused the video and tried the code.... and finally I figured it ! thx !!

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

    you gave the crux of the async
    now i can finally learn FASTAPI
    thanks a ton buddy

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

    This guy is amazing. Respect

  • @RoshanDhakal-vi1nh
    @RoshanDhakal-vi1nh 8 месяцев назад +1

    thanks dude, i know you might not see this but thanks for your help.

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

    exellent bro! you are the only one❤

  • @ChandraShekhar-by3cd
    @ChandraShekhar-by3cd 2 года назад

    Thanks a lot for your detailed explanation. It really helped me solving one problem related to the sending mail notification.

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

    7:35 Worth mentioning at this point the difference between “stackless” and “stackful” coroutines. Python has the “stackless” kind, which is why the await keyword can only be used in the top level of an async-function, not anywhere else.

  • @CookieMonsteeerrr
    @CookieMonsteeerrr 3 года назад

    best explanation ever - including example and explanation. good work

  • @adwaithrajesh596
    @adwaithrajesh596 3 года назад +1

    I've been waiting for this video for months ❤️❤️❤️❤️

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

    AT FIRST I DIDN'T UNDERSTOOD BUT THE 2ND TIME IT WAS SO CLEAR! THANK YOU!!!!

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

    So clear about all informatiion. Tnx!

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

    Awesome work dude
    Thank you

  • @azr_sd
    @azr_sd 3 года назад

    very simply explained! Very well done Tim.

  • @emiliochaparro8401
    @emiliochaparro8401 3 года назад +1

    Yess! I was waiting for this for a long time

  • @KyleTennison-v1q
    @KyleTennison-v1q Год назад

    ive been trying to learn this for so long lmfao u made it so easy

  • @RiskyRiskForRiskers
    @RiskyRiskForRiskers 3 года назад +1

    THIS VIDEO IS AWESOME. THANK YOU SO MUCH FOR SHARING THIS WITH US.

  • @rotichbill637
    @rotichbill637 3 года назад +1

    Wow great introduction into asyncio. Thanks!!

  • @ElinLiu0823
    @ElinLiu0823 3 года назад

    I am building my own spider Project and hope this tourial might work for me,you teached so detailed,i love it

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

    Nicely explained such a complicated topic master tim. It's a good tutorial.

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

    Thank you!! It was hard for me to grasp all this just from the asyncio documentation

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

    This was very interesting, thank you. But it looks like you could get into all kinds of timing issues. A follow up to this might be how to identify time issues and overcome or prevent them?

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

    Thanks Tim! Great video

  • @j.javiergalvez7934
    @j.javiergalvez7934 2 года назад

    Terrific job! Finally, I start understanding this topic :)

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

    Starts at 4:30

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

    Thank you, Tim. This video saved me a lot of time..

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

    SUper clear. Thanks!!

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

    damnn ... i have never seen a teacher like TIM

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

    Excellent demo & explainations!

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

    I noticed that, In the cosole, Task1 or Task2 and alike will only be said that they are pending If the value returning from them is being printed

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

    I learnt from this
    Thanks a lot

  • @emanuelh2020
    @emanuelh2020 3 года назад

    I love your videos, you have high quality content, Tim

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

    Best simple explain, thanks

  • @mohamed-muneer
    @mohamed-muneer 3 года назад +1

    Process of Querying the database should also be a coroutine when using await?

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

    Too good Tim.. 🎉

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

    great video tim, I am a Typescript developer but I use python too. I was wondering if handling errors with Futures is like handler errors with promises in Typescript

  • @wannabedev2452
    @wannabedev2452 3 года назад

    I love this man.... exactly what i needed

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

    Thank you for making it so easy to follow.

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

    Awesome video, using this to help me understand some IoT applications in Azure

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

    At 16:00, why doesn't the execution take at least 10.5 seconds to fully complete? I get that it's smart to hand off while you await, but why doesn't the "main" object/function finish running the task before being considered completely done? Or is it that the task runs outside of the main function and when you pass back off the memory or CPU to the function it is technically complete once it runs the last line in that function which is print(finished)?
    Does the task ever get finished? I get the function completed, but does the task ever get compete itself? Like say it wasn't time.wait, but a different method that still caused a delay would it complete? That part is foggy.

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

      Ya that part confused me as well. Ask chat gpt!

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

    Thank you very well explained

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

    THANK YOU!!!!!

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

    Thank you so much! I could understand this clearly 🤯

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

    you are the best:)

  • @gigabytechanz9646
    @gigabytechanz9646 3 года назад

    Really interesting! Good Explanation!!

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

    very helpful intro, cheers

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

    Thank you for making the awesome video

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

    clear explanation

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

    It was very useful thanks dude

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

    Cool, the video I needed to really understand this!

  • @Morimove
    @Morimove 7 месяцев назад

    at 12:57 i got what i needed!

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

    Great video. Thanks so much, very helpful.

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

    wonderful class! thank you so much!

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

    If we were to add the "print('done')" part in my code below (exactly Tim's code at 16:56, but with the extra print), why would the 'done' message not be printed? The program prints 'finished' then exits. Is it because the execution of 'main' finished, therefore the execution of 'foo' is "prematurely" must be finished too, because "foo" was called from within "main"? (similar to how daemon threads work..?)
    import asyncio
    async def main():
    print('tim')
    task = asyncio.create_task(foo('text'))
    await asyncio.sleep(0.5)
    print('finished')
    async def foo(text):
    print(text)
    await asyncio.sleep(10)
    print('done')
    asyncio.run(main())

  • @JJ-pn8lb
    @JJ-pn8lb 3 года назад +1

    Thank you, very nice video

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

    thanks man you're very helpfull

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

    kind of new to programming, one thing that is somewhat confusing me is, howcome he is able to execute foo function within the main, before defining it.

  • @jonorgames9880
    @jonorgames9880 3 года назад

    Interesting topic. As a beginner, it seems to me, that the artificial 'sleep command' hands tasks over nicely, but, what about a nasty huge for-loop that bogges down a program? Then it seems "busy", and can NOT hand over a task (to, for example, the exit button) and the program seems to freeze.

    • @angelcaru
      @angelcaru 3 года назад

      This is for I/O stuff. Since a huge for loop is a data processing task, it needs to run it somehow.

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

    Great video. Is that the same as Celery does?

  • @viswatejaforu
    @viswatejaforu 3 года назад

    Nice explanation

  • @Das.Kleine.Krokodil
    @Das.Kleine.Krokodil 2 года назад

    Шикарно! Спасибо!

  • @IqbalHamid
    @IqbalHamid 3 года назад +1

    Weird! When I ran your code @08:44 , I got the error:
    RuntimeError: asyncio.run() cannot be called from a running event loop

    • @IqbalHamid
      @IqbalHamid 3 года назад +4

      Just figured out why: It is because I am using the spyder IDE which uses an event loop to run its python interpreter/console. The solution is to insert the following at teh top of your code:
      import nest_asyncio
      nest_asyncio.apply()

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

    Greate Content! Thanks

  • @ShivangiSingh-wc3gk
    @ShivangiSingh-wc3gk 2 года назад

    so only one task is actively running at a point in time ? (the coroutine waiting for something is pushed to the back?)

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

    In every other use of the word "synchronous" in the human language, it means things happening together, synchronized like "synchronized swimming." I get that having all routines using the same thread and not being unhinged from each other could be considered as synchronous in some way, but even a dictionary definition of synchronous is "occurring or existing at the same time." I wish the people who named these things had a better command of the English language.

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

    thank you for great content

  • @彭程-u5y
    @彭程-u5y 3 года назад

    Thanks, it helps me a lot

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

    Hi, when I use this code in python, it is ok but when I run the same code in anaconda v5 (spyder), the error will rise :
    "RuntimeError: asyncio.run() cannot be called from a running event loop"
    what should I do?