-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Proper way to use dynamic keys for TypedDict #9168
Comments
This should work:
Here's a somewhat similar situation that I have ran into:
and how to fix that:
|
ok so my above suggestion doesn't actually work, but this works:
on python 3.8 or newer: |
Okay, I'll try that. Though I don't like the cast, since it's different list of values. so if I happen to mismatch one I might bypass some type safety. Is there any way to convert a literal list of strings for use in the |
PEP 586 says that "Type checkers may optionally perform additional analysis" to make your code work as is, but mypy doesn't do that: https://www.python.org/dev/peps/pep-0586/#interactions-with-narrowing I can't figure out a way to do this without repeating the list of strings. I thought about creating a modified version of |
For fun, here's a terrible hack that currently works in mypy, and creates an error if the
|
Inferring literal types in some cases like these might be reasonable I guess, as long as it doesn't seem to generate many false positives (I don't think that it would). |
Related: this code should pass - from typing_extensions import TypedDict, Literal
from typing import Set
class SomeDict(TypedDict):
key1: int
key2: int
AllKeys = Literal['key1', 'key2']
s: Set[AllKeys] = {'key1'}
d: SomeDict = {k: 0 for k in s} since the key type is adequately constrained; but fails with
Stranger yet, this can be worked-around by replacing the dictionary comprehension with a naive assignment loop; which then passes. |
#6262 (comment) would save a lot of duplication if you could define a type that was "a key of this typeddict" |
Agree. It would be awesome to have something like TypeScript's keyof. |
Is there a way to use dynamic keys for a TypedDict which is properly typed? I have code like this:
Where
obj
is aTypedDict
that has the same type for the keys 'visible', 'value', 'locked'.I know that
name
is not a literal string, but it's been verified to belong to a set of literal strings that belong to the TypedDict.The text was updated successfully, but these errors were encountered: