wemake-python-styleguide
wemake-python-styleguide copied to clipboard
Forbid coroutines usage as boolean conditions
Rule request:
Restrict usage of coroutines (initialized, but not awaited) as boolean conditions
Thesis
Example:
async def some_coro() -> bool:
return True
if some_coro(): # The rule should fail at this line
pass
# Also, it should work with variable declaration
supposed_boolean = some_coro()
if supposed_boolean: # The rule should fail at this line
pass
If you use class-based awaitable with an overloaded __bool__
method and want to check its actual condition, you can use the following construction:
class MyCoro:
def __await__():
pass
def __bool___():
return True
coro_condition = bool(MyCoro()) # The rule is passed
Reasoning
This rule aims to prevent common errors that may occur due to overlooking the await
keyword before using coroutines in if statements.
linters and type checkers do not consider the usage of coroutines in if statements as an error since any type can be treated as a boolean, leading to subtle bugs.