TypeVar single constraint not allowed, why?

Ned Batchelder ned at nedbatchelder.com
Wed May 3 08:31:48 EDT 2017


On Tuesday, May 2, 2017 at 11:45:39 AM UTC-4, oliver wrote:
> The documentation for typing.TypeVar gives these two examples:
> 
>     T = TypeVar('T')  # Can be anything
>     A = TypeVar('A', str, bytes)  # Must be str or bytes
> 
> I was suprised to find out that the following does not work, exception says
> that TypeVar is not definable with only one constraint:
> 
>     A = TypeVar('A', type)  # Must be a type, like class Foo, etc (rather
> than an instance of a type)
> 
> The TypeVar source code explicitely forbids only one type constraint, what
> is the rationale behind this?
> 
> For those who wonder, my function parameter expects a type rather than an
> instance of a type, and returns a type.

Couldn't you simply annotate it as ": type", without using a TypeVar?

--Ned.



More information about the Python-list mailing list