#`async def` vs `def`

1 messages · Page 1 of 1 (latest)

olive escarp
#

I have a function in a separate file for querying the database called my_func, I call it from the bot command. What type of function is better to use and why? def or async def

livid osprey
#

async doesn't block main thread

leaden linden
#

You use async def if you need to await something inside

livid osprey
#

sync blocks

leaden linden
#

Just because a function is defined as async it doesn't mean it cannot block

olive escarp
leaden linden
#

Return has nothing to do with it

olive escarp
#

Hm

leaden linden
#

I said await

olive escarp
#

Can I have an example?

static peak
#

An example of what?

olive escarp
#

I just can't figure out what to use

static peak
#

If your db query code is blocking, then it doesn't matter. It's blocking regardless.

#

And you should switch to an async version of the db driver you're using.

olive escarp
#
@client.command() 
async def command(ctx):
   await my_func(id)


async def my_func(id):
   name = ... #call database with id
   return name

OR

@client.command() 
async def command(ctx):
   my_func(id)


def my_func(id):
   name = ... #call database with id
   return name
static peak
#

Quite literally doesn't matter if #call database is a synchronous function.

#
async def get_member(id: int):
   return sync_db.get_member(id)

Still blocking whlie sync_db.get_member() is being executed.

async def get_member(id: int):
   return await async_db.get_member(id)

Now it's actually async since the code within the function is also async.

olive escarp
static peak
#

which is blocking.

#

switch to aiosqlite

olive escarp