PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to use await in a python lambda

 November 04, 2022     async-await, asynchronous, lambda, python, python-3.x     No comments   

Issue

I'm trying to do something like this:

mylist.sort(key=lambda x: await somefunction(x))

But I get this error:

SyntaxError: 'await' outside async function

Which makes sense because the lambda is not async.

I tried to use async lambda x: ... but that throws a SyntaxError: invalid syntax.

Pep 492 states:

Syntax for asynchronous lambda functions could be provided, but this construct is outside of the scope of this PEP.

But I could not find out if that syntax was implemented in CPython.

Is there a way to declare an async lambda, or to use an async function for sorting a list?


Solution

You can't. There is no async lambda, and even if there were, you coudln't pass it in as key function to list.sort(), since a key function will be called as a synchronous function and not awaited. An easy work-around is to annotate your list yourself:

mylist_annotated = [(await some_function(x), x) for x in mylist]
mylist_annotated.sort()
mylist = [x for key, x in mylist_annotated]

Note that await expressions in list comprehensions are only supported in Python 3.6+. If you're using 3.5, you can do the following:

mylist_annotated = []
for x in mylist:
    mylist_annotated.append((await some_function(x), x)) 
mylist_annotated.sort()
mylist = [x for key, x in mylist_annotated]


Answered By - Sven Marnach
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing