Skip to content

Type hint for covariant dict keys like Sequence #8688

Answered by Antyos
Antyos asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks for the explanation about the keys.

My actual desired function signature looks like:

def dict_key_union(d: dict[KEYS | int, int]):
    # My actual use case does different processing with the dict, but since it gets hung up here, I 
    d2 = dict(d)
    # ...

Because the dictionary keys can be a type other than str (i.e., int), I can't simply splat them with dict(**d).

However, that made me realize that I can stop overcomplicating my life and just do:

def dict_key_union(d: dict[KEYS | int, int] | dict[KEYS, int] | dict[int, int]):
    d2 = dict()
    for k, v in d.items():
        d2[k] = v

With that being said, does the dict union type hint error I noted seem like a bug?

def foo(d: 

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@Antyos
Comment options

Answer selected by Antyos
@erictraut
Comment options

@Antyos
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants