Hello, this is my first post here, so I’m sorry if this has already been discussed. I don’t see any PEPs related to this and my search of this forum and GitHub came back empty.
Proposal would be to add the following types:
If - for ternary operations
Equals for comparing straight equality ==. Seems like pyright does this but mypy doesn’t.
IsInstance to see if an object is a type.
Say I want type safety for a divisor I’m passing around, and I want to make sure someone doesn’t type zero before runtime.
TypeScript has the following:
type NotZero<N extends number> = N extends 0 ? never : N;
const num: NotZero<1> = 1;
const bad: NotZero<0> = 0;
The proposal here is to introduce a Python-equivalent.
type NonZero[N: number] = If[Equals[N, Literal[0]], Never, N]
This will help type checkers with branching logic, so instead of a Union type:
def get_animal_noise(pet: Dog|Cat) -> Literal['woof', 'meow']: ...
if get_animal_noise(Dog()) == "meow": ... # no error
You can provide more helpful type instructions:
def get_animal_noise[A: Dog|Cat](pet: A) -> If[
IsInstance[A, Dog], Literal['woof'], Literal['meow']
]: ...
if get_animal_noise(Dog()) == "meow": ... # Pylance(reportUnnecessaryComparison)