ruff/crates/red_knot_python_semantic/resources/mdtest/binary/booleans.md
Shaygan Hooshyari 0f0fff4d5a
[red-knot] Implement more types in binary and unary expressions (#13803)
Implemented some points from
https://github.com/astral-sh/ruff/issues/12701

- Handle Unknown and Any in Unary operation
- Handle Boolean in binary operations
- Handle instances in unary operation
- Consider division by False to be division by zero

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2024-10-20 01:57:21 +00:00

1.5 KiB

Binary operations on booleans

Basic Arithmetic

We try to be precise and all operations except for division will result in Literal type.

a = True
b = False

reveal_type(a + a)  # revealed: Literal[2]
reveal_type(a + b)  # revealed: Literal[1]
reveal_type(b + a)  # revealed: Literal[1]
reveal_type(b + b)  # revealed: Literal[0]

reveal_type(a - a)  # revealed: Literal[0]
reveal_type(a - b)  # revealed: Literal[1]
reveal_type(b - a)  # revealed: Literal[-1]
reveal_type(b - b)  # revealed: Literal[0]

reveal_type(a * a)  # revealed: Literal[1]
reveal_type(a * b)  # revealed: Literal[0]
reveal_type(b * a)  # revealed: Literal[0]
reveal_type(b * b)  # revealed: Literal[0]

reveal_type(a % a)  # revealed: Literal[0]
reveal_type(b % a)  # revealed: Literal[0]

reveal_type(a // a)  # revealed: Literal[1]
reveal_type(b // a)  # revealed: Literal[0]

reveal_type(a**a)  # revealed: Literal[1]
reveal_type(a**b)  # revealed: Literal[1]
reveal_type(b**a)  # revealed: Literal[0]
reveal_type(b**b)  # revealed: Literal[1]

# Division
reveal_type(a / a)  # revealed: float
reveal_type(b / a)  # revealed: float
b / b  # error: [division-by-zero] "Cannot divide object of type `Literal[False]` by zero"
a / b  # error: [division-by-zero] "Cannot divide object of type `Literal[True]` by zero"

# bitwise OR
reveal_type(a | a)  # revealed: Literal[True]
reveal_type(a | b)  # revealed: Literal[True]
reveal_type(b | a)  # revealed: Literal[True]
reveal_type(b | b)  # revealed: Literal[False]