How To Make ANY Function Asynchronous In Python 3.12

Indently
25 Jan 202405:52

Summary

TLDRこのビデオチュートリアルでは、Pythonで非同期関数に変換する方法を学びます。特に、同期モジュールであるrequestsモジュールを例に、APIからJSONをリクエストする際にコードの実行をブロックしないようにする技術を紹介します。asyncioモジュールとasyncio.to_threadを使用して、任意の同期関数を非同期に実行する方法を実践的に説明します。さらに、複数のウェブサイトのステータスを非同期にチェックするサンプルスクリプトを作成する過程も解説します。このビデオは、非同期プログラミングの基礎を学びたい方にとって価値あるリソースです。

Takeaways

  • 🐍 Pythonの非同期プログラミングの重要性を説明しています。
  • 🌐 'requests'モジュールは同期的であり、コードのブロックを防ぎたい場合があると述べています。
  • ⚙️ 'pip install requests'コマンドを使って、'requests'モジュールをインストールする方法を紹介しています。
  • 🔍 'requests'から'response'タイプをインポートする方法を説明しています。
  • 🖥️ 複数のウェブサイトのステータスを非同期でチェックするサンプルスクリプトを作成する過程を示しています。
  • 🛠️ 'asyncio'と'from asyncio import task'をインポートすることで非同期関数を作成する方法を説明しています。
  • 📡 'await asyncio.to_thread()'を使用して、任意の同期関数を非同期関数に変換する方法を説明しています。
  • 🌍 特定のURLからステータスコードを非同期に取得する具体的な方法を示しています。
  • 🏃 'async def main()'を使用して非同期タスクを実行し、結果を表示する方法を説明しています。
  • ✨ Pythonで非同期プログラミングを活用することの便利さとパワフルさを強調しています。

Q & A

  • Pythonで非同期関数に変換する方法は何ですか?

    -非同期IO(asyncio)モジュールの`to_thread`関数を使用して、同期関数を非同期関数に変換することができます。

  • `requests`モジュールを非同期で使用するにはどうすればよいですか?

    -`asyncio.to_thread`を使って、`requests.get`関数を非同期に実行できます。

  • 非同期関数で戻り値の型を指定するにはどうすればよいですか?

    -関数の定義時に型注釈を使って戻り値の型を指定できます。例えば、`async def fetch_status(url: str) -> dict:`のようにします。

  • 複数のウェブサイトのステータスを非同期でチェックするにはどうすればよいですか?

    -非同期関数を定義し、`asyncio.create_task`を使ってそれぞれのウェブサイトのステータスを非同期にフェッチするタスクを作成します。

  • `asyncio.run`の役割は何ですか?

    -`asyncio.run`は、非同期プログラムのメインエントリポイントを実行するために使用されます。

  • `asyncio.to_thread`の引数には何を指定しますか?

    -実行したい関数、その関数に渡す引数、およびキーワード引数を指定します。

  • 非同期関数の中で`await`キーワードの役割は何ですか?

    -`await`キーワードは、非同期実行を待機し、その結果を取得するために使用されます。

  • 非同期プログラミングで`Task`型の重要性は何ですか?

    -`Task`型は、非同期に実行されるコルーチンを管理し、その結果を後で取得できるようにするために使用されます。

  • 同期関数を非同期関数に変換するメリットは何ですか?

    -ブロッキング操作を避け、アプリケーションのレスポンス性を向上させることができます。

  • 非同期関数を使う際に、なぜ型注釈を使うのが良いとされていますか?

    -型注釈を使用することで、関数の入力と戻り値の型が明確になり、コードの可読性と保守性が向上します。

Outlines

00:00

🐍 Python 非同期プログラミング入門

このビデオでは、Pythonで同期関数を非同期関数に変換する方法を紹介しています。特に、同期モジュールである'requests'モジュールを例に取り、APIからJSONデータを取得する際にコードのブロッキングを防ぐ方法に焦点を当てています。まず、'requests'モジュールのインストールから始め、その後、タイプアノテーションを使用し、非同期関数を作成する手順を詳細に説明しています。この関数は、ウェブサイトのステータスを非同期的にチェックする例として用いられ、'asyncio.to_thread'を使って任意の同期関数を非同期に変換する方法を示しています。最終的に、複数のウェブサイトのステータスを同時に取得するデモンストレーションが行われます。

05:01

🚀 非同期処理の実践と応用

このパートでは、非同期関数を使用して複数のウェブサイトのステータスを同時にチェックする方法を実践しています。具体的には、'asyncio'を使用して'apple.com'と'google.com'のステータスを非同期的に取得するデモが示されています。このプロセスでは、各ウェブサイトからのレスポンスを待つことなく、並行してリクエストを送信することが強調されています。また、非同期関数をより多くのタスクに適用する際の'gather'メソッドの使用も簡単に触れられています。最後に、視聴者にフィードバックを求める形でビデオが締めくくられています。

Mindmap

Keywords

💡非同期関数

非同期関数とは、他のタスクが実行される間、プログラムの実行をブロックしない関数です。このビデオでは、非同期関数を使用して複数のウェブサイトの状態を同時に確認する方法を説明しています。例えば、`asyncio`ライブラリを用いて、通常のブロッキングな`requests.get`関数を非同期的に実行する方法を示しています。

💡asyncio

`asyncio`はPythonで非同期プログラミングをサポートするためのライブラリです。このビデオでは、非同期タスクの作成や管理に`asyncio`を使用する方法を紹介しています。具体的には、`asyncio.create_task`を使用して非同期タスクを生成し、それを待つ方法が説明されています。

💡requests

`requests`はPythonでHTTPリクエストを送信するための同期ライブラリです。このビデオでは、`requests`を使ってAPIからJSONデータを取得する例を示しており、それを非同期に変換する方法を教えています。

💡ブロッキング

ブロッキングとは、プログラムの実行が外部イベント(例えば、ネットワークリクエストの完了)を待つ間、停止することを指します。ビデオでは、通常の`requests`モジュールがブロッキングであること、そしてそれがプログラムの効率にどのように影響するかを説明しています。

💡非同期I/O

非同期I/Oとは、入出力操作が即座に完了することなくプログラムの実行を続けられるようにするプログラミングパラダイムです。このビデオでは、`asyncio`ライブラリを用いた非同期I/Oの実装方法を解説しています。

💡タスク

タスクとは、非同期関数の実行を表すオブジェクトです。このビデオでは、`asyncio.create_task`を使って非同期関数からタスクを作成し、これを非同期に実行する方法を説明しています。

💡async/await

`async`と`await`は、Pythonの非同期プログラミングを可能にするキーワードです。`async`で定義された関数は非同期関数となり、`await`を用いてその関数の実行を待つことができます。ビデオではこれらのキーワードを使用して非同期コードを書く方法を教えています。

💡ステータスコード

ステータスコードは、HTTPレスポンスの一部であり、リクエストが成功したか、あるいはどのような種類のエラーが発生したかを示します。このビデオでは、非同期に取得したレスポンスからステータスコードを取り出し、ウェブサイトの状態をチェックする例を示しています。

💡do_to_thread

`do_to_thread`はこのビデオには直接は現れませんが、`asyncio.to_thread`のような関数を指している可能性があり、それは同期的な関数を非同期的に実行するために新しいスレッドで実行することを可能にします。このコンセプトは、同期関数を非同期関数に変換するための方法としてビデオで説明されています。

💡gather

`gather`は`asyncio`ライブラリの関数で、複数の非同期タスクを並行して実行し、全ての結果が揃うのを待つことができます。ビデオの最後で、非同期タスクが多数ある場合に`gather`を使用することを提案しており、これは非同期プログラミングにおける効率的なパターンです。

Highlights

I'm going to be teaching you how you can turn any synchronous function into an asynchronous function in Python

this is quite important because you might be working with a module such as the requests module which is a synchronous module which kind of sucks because if you're making a request for some Json from some sort of API you might not want that to block your code

we can create an asynchronous function or a co-routine and call it fetch status which will take a URL of type string and it's going to return to us a dictionary that we will Define now

this is the juicy part this is the way you can turn any synchronous function into an asynchronous function so await asyn iio do2 thread so that's going to St it on a separate thread

and it's as simple as that to turn any function into an asynchronous function

we were able to send the request for both of them and then once both of them got these status back we were able to use those statuses anyway it was as simple as that to turn a synchronous function into an asynchronous function

Transcripts

play00:00

this video was brought to you by IND

play00:02

dentle IO learning python Made Simple in

play00:05

today's lesson I'm going to be teaching

play00:07

you how you can turn any synchronous

play00:09

function into an asynchronous function

play00:12

in Python and this is quite important

play00:15

because you might be working with a

play00:17

module such as the requests module which

play00:19

is a synchronous module which kind of

play00:21

sucks because if you're making a request

play00:24

for some Json from some sort of API you

play00:27

might not want that to block your code

play00:29

and anyway to get started we're going to

play00:31

open up the terminal and type in PIP

play00:33

install requests because that's what I'm

play00:35

going to be using as an example for this

play00:38

tutorial and once we have that we can

play00:40

import requests and since I'm going to

play00:43

be using a type annotation from requests

play00:45

I'm going to import from

play00:47

requests import the

play00:50

response Now by this point you should be

play00:53

quite familiar with how the requests

play00:55

module actually works if you want a

play00:57

response you would say response of type

play00:59

response response equals

play01:02

requests do getet and You' pass in your

play01:05

url then once you get the response you

play01:08

can call response. Json if you have an

play01:12

API or you can even just get some other

play01:15

information from that response once you

play01:17

make that request but once again this is

play01:19

a blocking request and what if we want

play01:22

to check many websites or various

play01:24

websites at the exact same time well to

play01:27

demonstrate how we can do that I'm just

play01:28

going to create a sample script that

play01:30

checks whether multiple websites are

play01:32

online and to do that before we actually

play01:35

move any further I'm going to import

play01:36

async iio and from asyn iio I'm going to

play01:40

import the task type then down below we

play01:43

can create an asynchronous function or a

play01:46

co- routine and call it fetch

play01:52

status and call it fetch status which

play01:55

will take a URL of type string and it's

play01:58

going to return to us

play02:00

a dictionary that we will Define now

play02:03

first of all we will add some beautiful

play02:05

print message which will say fetching

play02:08

status for and we will pass in the URL

play02:12

then we can create our response of type

play02:14

response which will equal a weight and

play02:18

this is the juicy part this is the way

play02:20

you can turn any synchronous function

play02:22

into an asynchronous function so await

play02:26

asyn iio do2 thread so that's going to

play02:29

St it on a separate thread and as the

play02:33

arguments we can pass in a function the

play02:35

arguments for that function and the

play02:37

keyword arguments for that function so

play02:39

in this case since we're using get we're

play02:41

going to call request.get and the only

play02:44

argument we want to pass in really right

play02:46

now is the URL so we're just going to

play02:48

pass it in as is and for the arguments

play02:51

you'd want to pass them in in order the

play02:54

same way you would pass them in for get

play02:55

if you hover over get you'll see that we

play02:57

have the URL then we have the parameters

play02:59

and so on now my Pi does complain to me

play03:02

so what I do is pass in none for the

play03:04

rest and my Pi does not complain anymore

play03:07

and it's as simple as that to turn any

play03:09

function into an asynchronous function

play03:13

now that we have that there we can print

play03:15

that we got it so I'm just going to

play03:16

print done and we're going to return a

play03:19

dictionary with the status which will be

play03:22

the response. status code and which URL

play03:25

that was

play03:26

for now let's try to use this by

play03:29

creating our main entry point So async

play03:31

Def Main and that returns

play03:34

none and first we'll create an apple

play03:37

task and I don't like how little space

play03:40

we have so I'll make some more Apple

play03:42

task of type task which returns a

play03:44

dictionary is going to equal an asyn i.

play03:48

create task and we're going to pass in

play03:51

Fetch status with the URL that we want

play03:53

to fetch the status for in this case I'm

play03:56

going to pass in

play03:58

apple.com

play04:00

but you can pass in whatever website you

play04:02

want and then I'm going to duplicate

play04:04

that and I'm going to call it Google

play04:07

task and we're going to pass in

play04:09

google.com then of course we need to

play04:11

wait for these tasks to complete so

play04:14

Apple status of type dictionary is going

play04:16

to equal await Apple

play04:18

task and the same thing goes for Google

play04:22

task and of course we want different

play04:24

names then all that's left for us to do

play04:27

here is to display the results so print

play04:30

Apple status and print Google

play04:33

status and of course we need to run this

play04:37

so if name is equal to

play04:42

main we're going to run our script using

play04:45

asyn

play04:46

i.run with the main entry point being

play04:50

our main function now with that we can

play04:52

actually test this script by tapping on

play04:54

run and what you should notice in the

play04:56

console is that we're able to fetch the

play04:58

status for both both of these websites

play05:00

asynchronously we did not need to wait

play05:02

for this one to complete before moving

play05:05

on to Google we were able to send the

play05:07

request for both of them and then once

play05:09

both of them got these status back we

play05:11

were able to use those statuses anyway

play05:14

it was as simple as that to turn a

play05:17

synchronous function into an

play05:18

asynchronous function and yes you could

play05:21

use gather if you have much if you have

play05:23

many more websites you don't need to do

play05:24

it one by one this is very labor

play05:26

intensive if you have lots of tasks but

play05:29

you get the point now you know how to

play05:30

make functions that are not asynchronous

play05:32

asynchronous that's another very

play05:34

difficult sentence I don't know why I

play05:36

decided to say it like that anyway

play05:38

that's actually all I wanted to cover in

play05:40

today's video do let me know in the

play05:41

comment section down below whether this

play05:43

helped with anything or whether you have

play05:44

some added information I would love to

play05:46

hear about that but otherwise as always

play05:49

thanks for watching and I'll see you in

play05:50

the next video

Rate This

5.0 / 5 (0 votes)

Do you need a summary in English?