PEP 646: Be more explicit about grammar changes needed (#1880)

This commit is contained in:
Matthew Rahtz 2021-03-31 18:36:09 +01:00 committed by GitHub
parent a841aeeb77
commit 47cb40ea58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 23 additions and 5 deletions

View File

@ -148,6 +148,10 @@ Specification
In order to support the above use cases, we introduce ``TypeVarTuple``. This serves as a placeholder not for a single type but for an *arbitrary* number of types, and behaving like a number of ``TypeVar`` instances packed in a ``Tuple``.
In addition, we introduce a new use for the star operator: to 'unpack'
``TypeVarTuple`` instances, in order to access the type variables
contained in the tuple.
Type Variable Tuples
--------------------
@ -697,11 +701,25 @@ these type annotations.
Backwards Compatibility
=======================
The grammar changes necessary for unpacking of type variable tuples using
the star operator are almost all covered by PEP 637. The one exception
is '``*args: *Ts``', which would require an additional change. (This
change could be avoided by simply mandating this be written
as ``Unpack[Ts]``, however.)
In order to use the star operator for unpacking of ``TypeVarTuple`` instances,
we would need to make two grammar changes:
1. Star expressions must be made valid in at least index operations.
For example, ``Tuple[*Ts]`` and ``Tuple[T1, *Ts, T2]`` would both
be valid. (This PEP does not allow multiple unpacked ``TypeVarTuple``
instances to appear in a single parameter list, so ``Tuple[*Ts1, *Ts2]``
would be a runtime error. Also note that star expressions would *not*
be valid in slice expressions - e.g. ``Tuple[*Ts:*Ts]`` is
nonsensical and should remain invalid.)
2. We would need to make '``*args: *Ts``' valid in function definitions.
In both cases, at runtime the star operator would call ``Ts.__iter__()``.
This would, in turn, return an instance of a helper class, e.g.
``UnpackedTypeVarTuple``, whose ``repr`` would be ``*Ts``.
If these grammar changes are considered too burdensome, we could instead
simply use ``Unpack`` - though in this case it might be better for us to
first decide whether there's a better option.
The ``Unpack`` version of the PEP should be back-portable to previous
versions of Python.