This rule raises an issue when the built-in input() function is called in an asynchronous function.
In Python’s asynchronous programming (using asyncio, Trio, or AnyIO), an event loop manages concurrent tasks
by having them yield control during time-consuming operations, enabling other tasks to run.
However, the synchronous input() function blocks the current thread until user input is received, and when called from a coroutine, it
blocks the entire event loop, preventing other tasks from executing and making the application unresponsive - effectively defeating the purpose of
asynchronous programming for applications requiring concurrent operations or user interaction.
You can use asyncio.to_thread() to run the input() function in a separate thread.
import asyncio
async def get_name():
print("Please enter your name:")
name = input() # Noncompliant
return name
import asyncio
async def get_name():
print("Please enter your name:")
name = await asyncio.to_thread(input) # Compliant
return name
You can use trio.to_thread.run_sync() to run the input() function in a separate thread.
import trio
async def get_name():
print("Please enter your name:")
name = input() # Noncompliant
return name
import trio
async def get_name():
print("Please enter your name:")
name = await trio.to_thread.run_sync(input) # Compliant
return name
You can use anyio.to_thread.run_sync() to run the input() function in a separate thread.
import anyio
async def get_name():
print("Please enter your name:")
name = input() # Noncompliant
return name
import anyio
async def get_name():
print("Please enter your name:")
name = await anyio.to_thread.run_sync(input) # Compliant
return name