El mié, 19 oct 2022 a las 10:02, Eric Traut (<eric@traut.com>) escribió:
I see. Yeah, you're using TypedDict in a way that the authors of PEP 589 apparently didn't contemplate.

First, you're using the "Alternate Syntax" which was provided (according to the PEP) for backward compatibility only. All versions of Python that are supported today do not have a need for this backward compatibility syntax, so I would expect its use to be waning at this point.

There are remaining use cases for the alternate syntax: if your keys are not valid identifiers or are Python keywords, you cannot use the class-based syntax. We recently changed the CPython docs to call out these use cases.
 

Second, you're using a dynamic expression for the second argument the the TypedDict alternate syntax, which the PEP calls out as something that static type checkers need not support.

> A type checker is only expected to accept a dictionary display expression as the second argument to TypedDict. In particular, a variable that refers to a dictionary object does not need to be supported, to simplify implementation.

For developers who are using TypedDict in accordance with its original intended purpose, I see utility in the errors that static type checkers currently generate in this case. If we were to suppress these errors and default the resulting type to dict[str, Any] in the presence of a dynamic expression, I think some developers would find that behavior to be surprising and non-intuitive because it would effectively render static type checking ineffective for that type. It would also not help with completion suggestions and other coding productivity features provided by language servers.

I agree that static type checkers should continue to error for dynamically generated TypedDicts. For Paul's use case, I would recommend a workaround like:

if TYPE_CHECKING:
    TD = dict[str, Any]
else:
    TD = TypedDict("TD", {k: v for ...}))
 

I think I'd want to see some additional signal that your use case is something that is more broadly desirable before adding this support to pyright.

 -Eric
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: jelle.zijlstra@gmail.com