ihoryam
ihoryam

Reputation: 2521

Use await in python REPL directly

I am wondering if there is a way to call async functions with await directly from python REPL ?

So having following code as example:

import aiohttp
import asyncio


async def somefunc():
    async with aiohttp.ClientSession() as session:
        host_url = 'https://somehost'
        async with session.get(host_url) as resp:
            response = await resp.json()
        return response

What I am looking for is an easy way to debug similar functions, basically I'd like to

>>> result = await somefunc()

I am aware that this can be done with

import asyncio

loop = asyncio.get_event_loop()
loop.run_until_complete(somefunc())

But using this approach I would need to either alter the body of somefunc to log the result of the response or use additional async function such as below to print the result

async def result_print():
    result = await somefunc()
    print(result)

loop = asyncio.get_event_loop()
loop.run_until_complete(result_print())

Summarising the things above, I am looking for a more convenient way to await async functions in the python REPL, maybe a custom REPL implementation that allows

>>> result = await somefunc()

Or possible there's a way to do that in python default repl that I am not aware of ?

Upvotes: 50

Views: 17867

Answers (2)

Matt Schlobohm
Matt Schlobohm

Reputation: 1378

I didn't understand how you couldn't get the response, it appears to be returned from loop.run_until_complete(somefunc())

I ran that code in the question with only one change to the url, using host_url = 'https://httpbin.org/json'

>>> response = loop.run_until_complete(mytest.somefunc())
>>> response
{'slideshow': {'author': 'Yours Truly', 'date': 'date of publication', 'slides': [{'title': 'Wake up to WonderWidgets!', 'type': 'all'}, {'items': ['Why <em>WonderWidgets</em> are great', 'Who <em>buys</em> WonderWidgets'], 'title': 'Overview', 'type': 'all'}], 'title': 'Sample Slide Show'}}
>>> 

Upvotes: -2

dirn
dirn

Reputation: 20759

The behavior you want is available if you launch the REPL using

python -m asyncio

Upvotes: 94

Related Questions