This rule raises an issue when the built-in input() function is called in an asynchronous function.

Why is this an issue?

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.

How to fix it in Asyncio

You can use asyncio.to_thread() to run the input() function in a separate thread.

Code examples

Noncompliant code example

import asyncio

async def get_name():
    print("Please enter your name:")
    name = input() # Noncompliant
    return name

Compliant solution

import asyncio

async def get_name():
    print("Please enter your name:")
    name = await asyncio.to_thread(input) # Compliant
    return name

How to fix it in Trio

You can use trio.to_thread.run_sync() to run the input() function in a separate thread.

Code examples

Noncompliant code example

import trio

async def get_name():
    print("Please enter your name:")
    name = input() # Noncompliant
    return name

Compliant solution

import trio

async def get_name():
    print("Please enter your name:")
    name = await trio.to_thread.run_sync(input) # Compliant
    return name

How to fix it in AnyIO

You can use anyio.to_thread.run_sync() to run the input() function in a separate thread.

Code examples

Noncompliant code example

import anyio

async def get_name():
    print("Please enter your name:")
    name = input() # Noncompliant
    return name

Compliant solution

import anyio

async def get_name():
    print("Please enter your name:")
    name = await anyio.to_thread.run_sync(input) # Compliant
    return name

Resources

Documentation

Articles & blog posts