'What are the implications of using a variable declared outside of an async context as a placeholder for its return values?
I understand that if the variable was declared outside of the function, it should be marked as global
. But what about this case? Is it safe to do something like:
async def foo():
items = []
async with SomeClient() as client:
fetched_items = await client.get_items()
for item in fetched_items:
items.append(item)
return items
Solution 1:[1]
Yes it is completely safe. with
statements do not create a new scope.
As for your code, you can easily refactor it:
async def foo():
async with SomeClient() as client:
return list(await client.get_items())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bharel |