I think isinstance() is a distraction. Sorry for that. The intent when Type[] was introduced was that it would describe a class object. TypedDict is an odd case because it uses runtime erasure. (There is also an issue around the constructor signature, so there is a silent assumption that constructors follow Liskov.) But Union etc. are not class objects.
Could we nevertheless forge ahead and widen the meaning of Type[]? I suppose so. But I think it would reduce clarity about the intent of the user. With TypeForm, I would expect the argument to be introspected. An example might be a function that renders a type prettier than the default str(). Or a JSON validator generator. With Type, I would expect the class to be instantiated.
—Guido
On 2/4/21 11:33 PM, Stefan van der Walt wrote:
> The question raised on the GitHub issue [0], "Why can't we make `Type[T]` also work for other special forms?", will likely come up for others reading this too. Would it be worth adding a sentence to explain?
>
> [0] https://github.com/python/mypy/issues/9773#issuecomment-736810721
Guido I tried to write up an explanation for this question, but couldn't
come up with a very strong answer. Could you, Ivan, or Jukka (on CC)
elaborate why it would be a bad idea to widen `Type` such that typing
special forms like `Optional[str]` or `Any` would be assignable to it?
My lukewarm attempt to explain the current rationale is at the bottom of
this email.
Personally I think it really *would* be a lot easier to just widen
Type[T] to also include typing special forms. It's unclear to me why
it's specifically important to have it only match things that can be
used in isinstance().
It doesn't even do that job perfectly at the moment:
`isinstance(MyTypedDict(value=1), MyTypedDict)` fails at runtime with
TypeError but mypy treats `MyTypedDict` as assignable to `Type` anyway.
--
David Foster | Seattle, WA, USA
Contributor to TypedDict support for mypy
>>>>>>>>>>
Rejected Ideas
==============
Widen Type[T] to support all typing special forms
-------------------------------------------------
`Type` was [designed] to only be used for things that can be the second
argument of `isinstance()`. And those things must be actual class
objects -- they cannot be typing special forms like `Any`,
`Optional[int]` or `List[str]`.
Since `Type` is restricted in this way, it is necessary to introduce a
new spelling, `TypeForm`, to include the additional special forms as well.
[designed]:
https://github.com/python/mypy/issues/8992#issuecomment-643369024
<<<<<<<<<<
--
--Guido (mobile)