Suppose I have code like this
async def fetch_text() -> str: return "text " async def show_something(): something = await fetch_text() print(something) Which is fine. But then I want to clean the data, so I do
async def fetch_text() -> str: return "text " def fetch_clean_text(text: str) -> str: text = await fetch_text() return text.strip(text) async def show_something(): something = fetch_clean_text() print(something) (I could clean text inside show_something(), but let's assume that show_something() can print many things and doesn't or shouldn't know the proper way of cleaning them.)
This is of course a SyntaxError: 'await' outside async function. But—if this code could run—while the await expression is not placed inside a coroutine function, it is executed in the context of one. Why this behavior is not allowed?
I see one pro in this design; in my latter example, you can't see that show_something()'s body is doing something that can result in its suspension. But if I were to make fetch_clean_text() a coroutine, not only would it complicate things but would probably also reduce performance. It just makes little sense to have another coroutine that doesn't perform any I/O by itself. Is there a better way?
awaitneeds schedule. As the above suggestted, you can use a pure function after fetching.my_library.fetch_title(url)that makes a lot of internal calls that eventually lead to some IO. Now if I was to make it also async-compatible, I'd (probably?) have to duplicate half of my code, addingasyncandawaitstuff to methods, and in most cases doing so would probably make little sense.