Refactor Union, Tuple, and Callable by ilevkivskyi · Pull Request #308 · python/typing
Fixes #301 now List[Tuple[T, T]][int] == List[Tuple[int, int]]
Fixes #298 now Table = Tuple[T, List[T]] can be used as generic type alias (as in PEP 484 example)
Fixes #299 now class MyTup(Tuple[int, ...]): ... is allowed
Fixes #156 (well, it does not substitute the annotations, but makes this task simple even in complex cases, see example in tests)
Also this PR fixes some minor things that I have found while working on this:
List[Union](with bareUnion, i.e. without arguments),List[Optional],List[Generic[T]], andList[ClassVar[int]]are not valid and are prohibited now.Genericdid not evaluate forward references when asked, now it does.__qualname__was not copied on generic class subscription.- Type was not erased on instantiation of subclasses of concrete containers (
List,Set, etc). - There was an obscure bug in Python 2: sometimes
_abc_registrywas erased on instantiation.
The main idea of this PR is to fix the issues mentioned at the top by reusing the existing code. Namely, I pulled flattening and removing duplicates code from _Union and the tree calculation function _subs_tree from GenericMeta. As well I moved Tuple and Callable after GenericMeta and made them inherit the latter. So that now all types that could be generic store their info in common way using __origin__, __parameters__, __args__.
I tried to polish this, to be sure that nothing was broken in the process of "refactoring" (also to improve speed). There is no recursion, the substitution tree is recalculated only when necessary. Also I added a lot of tests and many comments/docstrings (also for things added in my recent PRs).
@gvanrossum Could you please take a look at this? I would like this to get into 3.6b3, so that it will have a chance to be thoroughly tested.