Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages to using "type" keyword in python type aliases

Prior to python 3.12, my understanding was that the line mta = int created a type alias named mta, but with 3.12, this line could (should?) be written as type mta = int, even if the prior syntax is still supported. These aren't interchangeable, though. For example, isinstance will accept the first as a legal second argument, but will fail with the second. (It seems that in the second case, isinstance(3, mta.__value__) works, but this seems awkward.)

I read this documentation to mean that the syntaxes are both supported to allow for backward compatibility, not that they are functionally different. Given this behavior, when is it advantageous to use the type keyword? Are there cases in which the simple (pre-3.12) assignment are inferior?

For example:

>>> mta = int
>>> isinstance(3, mta)
True
>>> type mta = int
>>> isinstance(3, mta)
...
TypeError: isinstance arg 2 must be a type, a tuple of types, or a union
like image 389
Peter N Avatar asked Aug 14 '26 22:08

Peter N


1 Answers

As previously stated in others' notes on this question, per PEP 695 type-statement aliases are meant to provide:

  • better generic type parameter syntax,
  • lazy evaluation of type aliases,
  • better differentiation from ordinary variables (although TypeAlias, too, provided this).

It is worth noting that not only, as you point out, type statements aren't a full replacement for TypeAlias-style aliases, but they may have very well never been intended to be. Whether or not this is a design bug has been hotly debated, including here (this thread has some good insights).

like image 115
Julian Mehnle Avatar answered Aug 17 '26 10:08

Julian Mehnle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!