I reported this in github, but I am wondering if my sense of what people use type aliases for is completely wrong.
But it seems to me that although PEP 695 type aliases are the blessed replacement for the now-deprecated typing.TypeAlias, they are functionally not suitable as replacement.
From the issue:
A type alias designated as such using the typing.TypeAlias
annotation could be used in many places that a PEP 695 type aliases cannot, including (at least) as a class’s parent class, in calls to isinstance
and issubclass
. All of of these have been used in various codebases I maintain.
As such typing.TypeAlias
should be un-deprecated, or the implementation of PEP 695 type aliases should be updated to work in all cases where a plain type should be.
With typing.TypeAlias
:
$ poetry run python3
Python 3.12.0 (main, Oct 4 2023, 06:27:34) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import typing
>>> StringAlias: typing.TypeAlias = str
>>> isinstance('test', StringAlias)
True
>>> issubclass(StringAlias, str)
True
>>> class GreaterString(StringAlias): pass
...
>>>
With PEP 695 type aliases:
$ poetry run python3
Python 3.12.0 (main, Oct 4 2023, 06:27:34) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type StringAlias = str
>>> isinstance('test', StringAlias)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
>>> issubclass(StringAlias, str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: issubclass() arg 1 must be a class
>>> class GreaterString(StringAlias): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: typealias() takes exactly 2 positional arguments (3 given)
>>>
The examples above are moderately trivial, but my actual use case is to make extremely long class names (typically generic classes) more manageable.
An actual of example of this being:
type ChassisMountable = _equip.Mountable[ChassisMount,ChassisSectionDescription]
class Engine(ChassisMountable, _equip.FixedMass, _equip.Equipment): ...
[snip: Several dozen other similar classes that also extend ChassisMountable]