Open NoamNol opened 4 weeks ago
I found we already have a typing.assert_type
that does something else, so the suggested name type_assert
will confuse people.
We can stay with the ensure_type
option or combine the two options:
ensure_type isinstance(animal, CanFlyProtocol)
My suggestion is to add a way to coerce type narrowing without any runtime change, by adding new
type_assert
and/orensure_type
.These functions do nothing at runtime! they only help with the types.
Why not
cast(int, arg)
?cast
completely replaces the type and we need to write a full new type.With type narrowing it's only necessary to limit the options of the existing type.
cast
is more dangerous because we ignore the previous type. with narrowing we just limit the options of the previous type.cast
can't doIntersection
(yet). explained below.Why
type_assert
and not a normalassert
?assert
makes it slower at runtime, and sometimes we careassert
can break things when improving types of an old code baseThe downsides:
assert
or if-else conditions at runtime, the coerced narrowing ignores the real type and is dangerous, almost likecast
.With Intersection type
Until we have
Intersection
type, this kind of things are problematic:Even
cast
can't help us, but we can narrow the type!Type checkers can understand
Intersection
when we narrow the type, great!But what if we don't want to change runtime behavior? for this we can replace
assert
with the suggestedtype_assert
orensure_type
!ensure_type with Not
See:
How to do
not isinstance
withensure_type
? we have two options:Add a similar
ensure_not_type
Wait for the
Not[]
type