Skip to content

Feature suggestion: ban implicit bool conversion in conditional expressions #3959

Description

@kkom

What does the Pyrefly team think about introducing an optional diagnostic rule that would ban implicit bool conversion in conditional expressions? (or just in general)

def get_temperature() -> int | None:
    """Returns None if data is missing, otherwise temperature in degrees Celsius rounded to the nearest integer."""
    return 0

temperature = get_temperature()

if not temperature:
    raise Exception("Temperature sensor broken, aborting program")

# we now have a bug, because `0` is a perfectly fine value, but it was discarded in the early return above

process_temperature(temperature)

It's a very common source of bugs in production code (other scenarios are None vs legitimately empty lists). As far as I remember from my time at Facebook – a related "sketchy null check" rule in Hack led to fixing a lot of bugs like that.

It's definitely opinionated and arguably might better belong to a linter, but hinges on reliable type inference that's unavailable in Python linters today. That's why I'm creating this issue in a type checker repo.

PS: See microsoft/pyright#6488 for a related discussion on Pyright's repository with some community support & discussions on possible semantics (microsoft/pyright#6488 (reply in thread) is IMO useful to see).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions