TypeVar single constraint not allowed, why?

oliver oliver.schoenborn at gmail.com
Thu May 4 11:00:16 EDT 2017


On Wed, 3 May 2017 at 18:36 Gregory Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Ned Batchelder wrote:
> > Couldn't you simply annotate it as ": type", without using a TypeVar?
>
> Not if you want to constrain two types to be the same type.
>
>
Exactly! It would be a lot more expressive to write something like (with
Type assumed imported from typing module):

def func(a: type, b: type) -> Tuple[Type(a), Type(b)]:
    ...

This will not work because a and b are not globals. I could use strings but
this is a hack / language wart as far as I'm concerned (the language should
be extended so we don't have to resort to a lowly string). I suppose I
could do:

def func(a: type, b: type) -> Tuple[TypeVar['a'], TypeVar['b']]:
    ...

but this is not pythonic (not clean, simple), and too easy to have typo.
Same with forward declarations, where a class references itself in an
annotation: we should not have to resort to a string to express this, very
clunky and hacky.



> --
> Greg
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
Oliver
My StackOverflow contributions
My CodeProject articles
My Github projects
My SourceForget.net projects



More information about the Python-list mailing list