Thanks to visit codestin.com
Credit goes to github.com

Skip to content

bpo-43224: Add more tests for typevar substitution #31844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from typing import TypeAlias
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
from typing import TypeGuard
from typing import _determine_typevar_substitution
import abc
import textwrap
import typing
Expand Down Expand Up @@ -843,6 +844,125 @@ class C(Generic[Unpack[Ts]]): pass
self.assertNotEqual(C[Unpack[Ts1]], C[Unpack[Ts2]])


class TypeVarSubstitutionTests(BaseTestCase):

def test_valid_substitution(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')
Ts = TypeVarTuple('Ts')

# These are tuples of (typevars, args, expected_result).
test_cases = [
# TypeVars only
((T1,), (int,), {T1: int}),
((T1,), (tuple[int, ...],), {T1: tuple[int, ...]}),
((T1,), (Unpack[tuple[int]],), {T1: int}),
((T1, T2), (int, str), {T1: int, T2: str}),
((T1, T2), (tuple[int, ...], tuple[str, ...]), {T1: tuple[int, ...], T2: tuple[str, ...]}),
((T1, T2), (Unpack[tuple[int, str]],), {T1: int, T2: str}),
# TypeVarTuple only
((Ts,), (), {Ts: ()}),
((Ts,), (int,), {Ts: (int,)}),
((Ts,), (tuple[int, ...],), {Ts: (tuple[int, ...],)}),
((Ts,), (Unpack[tuple[int]],), {Ts: (int,)}),
((Ts,), (int, str), {Ts: (int, str)}),
((Ts,), (tuple[int, ...], tuple[str, ...]), {Ts: (tuple[int, ...], tuple[str, ...])}),
((Ts,), (Unpack[tuple[int, ...]],), {Ts: (Unpack[tuple[int, ...]],)}),
# TypeVarTuple at the beginning
((Ts, T1), (int,), {Ts: (), T1: int}),
((Ts, T1), (tuple[int, ...],), {Ts: (), T1: tuple[int, ...]}),
((Ts, T1), (int, str), {Ts: (int,), T1: str}),
((Ts, T1), (int, str, float), {Ts: (int, str), T1: float}),
((Ts, T1), (Unpack[tuple[int, ...]], str), {Ts: (Unpack[tuple[int, ...]],), T1: str}),
((Ts, T1), (Unpack[tuple[int, ...]], str, bool), {Ts: (Unpack[tuple[int, ...]], str), T1: bool}),
# TypeVarTuple at the end
((T1, Ts), (int,), {T1: int, Ts: ()}),
((T1, Ts), (int, str), {T1: int, Ts: (str,)}),
((T1, Ts), (int, str, float), {T1: int, Ts: (str, float)}),
((T1, Ts), (int, Unpack[tuple[str, ...]]), {T1: int, Ts: (Unpack[tuple[str, ...]],)}),
((T1, Ts), (int, str, Unpack[tuple[float, ...]]), {T1: int, Ts: (str, Unpack[tuple[float, ...]],)}),
# TypeVarTuple in the middle
((T1, Ts, T2), (int, str), {T1: int, Ts: (), T2: str}),
((T1, Ts, T2), (int, float, str), {T1: int, Ts: (float,), T2: str}),
((T1, Ts, T2), (int, Unpack[tuple[int, ...]], str), {T1: int, Ts: (Unpack[tuple[int, ...]],), T2: str}),
((T1, Ts, T2), (int, float, Unpack[tuple[bool, ...]], str), {T1: int, Ts: (float, Unpack[tuple[bool, ...]],), T2: str}),
((T1, Ts, T2), (int, Unpack[tuple[bool, ...]], float, str), {T1: int, Ts: (Unpack[tuple[bool, ...]], float), T2: str}),
((T1, Ts, T2), (int, complex, Unpack[tuple[bool, ...]], float, str), {T1: int, Ts: (complex, Unpack[tuple[bool, ...]], float), T2: str})
]
for typevars, args, expected_result in test_cases:
with self.subTest(f'typevars={typevars}, args={args}'):
self.assertEqual(
expected_result,
_determine_typevar_substitution(
cls=None, params=typevars, args=args
)
)

def test_too_few_args_raises_exception(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')

# We don't include test cases including TypeVarTuples because we
# decided not to implement arity checking of variadic generics
# in order to reduce complexity.
test_cases = [
# One TypeVar: invalid if 0 args
((T1,), ()),
((T1,), (Unpack[tuple[()]],)),
# Two TypeVars: invalid if <= 1 args
((T1, T2), (int,)),
((T1, T2), (Unpack[tuple[int]],)),
]
for typevars, args in test_cases:
with self.subTest(f'typevars={typevars}, args={args}'):
with self.assertRaises(TypeError):
_determine_typevar_substitution(
cls=None, params=typevars, args=args
)

def test_too_many_args_raises_exception(self):
T1 = TypeVar('T1')
T2 = TypeVar('T2')

# We don't include test cases including TypeVarTuples because we
# decided not to implement arity checking of variadic generics
# in order to reduce complexity.
test_cases = [
# One TypeVar: invalid if >= 2 args
((T1,), (int, int)),
((T1,), (Unpack[tuple[int, int]],)),
((T1,), (Unpack[tuple[int]], Unpack[tuple[int]])),
# Two TypeVars: invalid if >= 3 args
((T1, T2), (int, int, int)),
((T1, T2), (Unpack[tuple[int, int, int]],)),
((T1, T2), (Unpack[tuple[int]], Unpack[tuple[int]], Unpack[tuple[int]])),
]

for typevars, args in test_cases:
with self.subTest(f'typevars={typevars}, args={args}'):
with self.assertRaises(TypeError):
_determine_typevar_substitution(
cls=None, params=typevars, args=args
)

def test_too_many_typevartuples_raises_exception(self):
T = TypeVar('T')
Ts = TypeVarTuple('Ts')

test_cases = [
((T, Ts, Ts), (int, str)),
((Ts, T, Ts), (int, str)),
((Ts, Ts, T), (int, str))
]

for typevars, args in test_cases:
with self.subTest(f'typevars={typevars}, args={args}'):
with self.assertRaises(TypeError):
_determine_typevar_substitution(
cls=None, params=typevars, args=args
)


class UnionTests(BaseTestCase):

def test_basics(self):
Expand Down
56 changes: 39 additions & 17 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1269,11 +1269,6 @@ def __getitem__(self, args):
if (self._paramspec_tvars
and any(isinstance(t, ParamSpec) for t in self.__parameters__)):
args = _prepare_paramspec_params(self, args)
elif not any(isinstance(p, TypeVarTuple) for p in self.__parameters__):
# We only run this if there are no TypeVarTuples, because we
# don't check variadic generic arity at runtime (to reduce
# complexity of typing.py).
_check_generic(self, args, len(self.__parameters__))

new_args = self._determine_new_args(args)
r = self.copy_with(new_args)
Expand All @@ -1296,18 +1291,7 @@ def _determine_new_args(self, args):

params = self.__parameters__
# In the example above, this would be {T3: str}
new_arg_by_param = {}
for i, param in enumerate(params):
if isinstance(param, TypeVarTuple):
j = len(args) - (len(params) - i - 1)
if j < i:
raise TypeError(f"Too few arguments for {self}")
new_arg_by_param.update(zip(params[:i], args[:i]))
new_arg_by_param[param] = args[i: j]
new_arg_by_param.update(zip(params[i + 1:], args[j:]))
break
else:
new_arg_by_param.update(zip(params, args))
new_arg_by_param = _determine_typevar_substitution(self, params, args)

new_args = []
for old_arg in self.__args__:
Expand Down Expand Up @@ -1401,6 +1385,44 @@ def __iter__(self):
yield Unpack[self]


def _replace_degenerate_unpacked_tuples(
args: tuple[type, ...]
) -> tuple[type, ...]:
"""Replaces e.g. `*tuple[int]` with just `int` in `args`."""
new_args = []
for arg in args:
if (_is_unpacked_tuple(arg)
and not _is_unpacked_arbitrary_length_tuple(arg)):
arg_tuple = arg.__args__[0] # The actual tuple[int]
new_args.extend(arg_tuple.__args__)
else:
new_args.append(arg)
return tuple(new_args)


def _determine_typevar_substitution(cls, params, args):
args = _replace_degenerate_unpacked_tuples(args)
new_arg_by_param = {}
for i, param in enumerate(params):
if isinstance(param, TypeVarTuple):
j = len(args) - (len(params) - i - 1)
if j < i:
raise TypeError("Too few type arguments")
new_arg_by_param.update(zip(params[:i], args[:i]))
new_arg_by_param[param] = args[i: j]
new_arg_by_param.update(zip(params[i + 1:], args[j:]))
if any(isinstance(param, TypeVarTuple) for param in params[i + 1:]):
raise TypeError("Only one TypeVarTuple may be used in type parameters")
break
else:
# We only run this if there are no TypeVarTuples, because we
# don't check variadic generic arity at runtime (to reduce
# complexity of typing.py).
_check_generic(cls, args, len(params))
new_arg_by_param.update(zip(params, args))
return new_arg_by_param


# _nparams is the number of accepted parameters, e.g. 0 for Hashable,
# 1 for List and 2 for Dict. It may be -1 if variable number of
# parameters are accepted (needs custom __getitem__).
Expand Down