#🔒 returning value from async function

9 messages · Page 1 of 1 (latest)

open wraith
#

I'm trying out async and while I get the concept I struggle a bit with implementation.

How do you correctly return value from an async function?

I'm trying to grab some data from an API and return it as a dataframe. As I intend to use it via Pyodide I had to use pyfetch - thus if I understand correctly had to make my function async.

Here's what I've come up with:

async def get_data(category: str) -> pd.DataFrame:
    url = f"{BASEURL}{category}"
    response = await pyfetch(url, method="GET", headers=HEADERS)
    output = await response.json()
    return pd.DataFrame(output)


membersdf = await get_data("members")
st.write(membersdf)

it works but I'm not sure it's optimal way to do it. Do I have to put those awaits in each of those places?
Any suggestions greatly appreciated.

zealous gulchBOT
#

@open wraith

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

smoky wedge
#

if a function returns a coroutine object (like all async def's do), then yes. they need to be awaited

#

!e

import asyncio

async def my_coro_func():
    return 123

async def main() -> None:
    coro_obj = my_coro_func()
    print(coro_obj)

    result = await coro_obj
    print(result)

asyncio.run(main())
zealous gulchBOT
#

@smoky wedge :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | <coroutine object my_coro_func at 0x7f0bb4374880>
002 | 123
smoky wedge
pliant iron
#

You might be wondering whats the point of async if you always have to await your coroutine.
the real power of async is that you can create multiple coroutines and await them all at once.

zealous gulchBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.