4

I want to narrow an unambiguously defined dict[...] type in a superclass to a specific TypedDict in an inheriting class but I cannot figure out a way to specify a dict-based supertype that the TypedDict can get assigned to. I'm using pylance (standard).

The following works fine:

from typing import TypedDict

Base_t = TypedDict('Base_t', {})

class Base[T: Base_t]:
    def get(self) -> T:
        ...

class Implementation_t(TypedDict):
    one: str
    two: int

class Implementation[U: Implementation_t](Base[U]):
    def get(self) -> U:
        ...

However, if I want to specify Base_t more narrowly (i.e. specify the types of the map), along the idea of:

type Base_t = dict[str, str|int]

the type checker fails assigning Implementation_t to Base_t. I need a way to define a supertype to the TypedDict Implementation_t that specifies key & value types but not any specific fields.

N.B.: Naturally, Implementation_t's key and value types are subsets of Base_t's, respectively.

Is there a nice way to connotate this?

5
  • 1
    I don't have time to write a complete answer right now, but here's a start: Subtyping with dict Commented Oct 23 at 8:54
  • I've rewritten your code sample. Does it still match your intent? Commented Oct 23 at 9:03
  • Hi Anerdw, thanks for your suggestions. There's no immediate rush with my questions; if anyone (including myself) has a good answer it'd be great to see it added to this question. Thank you also for your effort editing my post but it had caused it to stray from its original intent and most details had been worded that way on purpose (most importantly, I insist on saying thanks!). Commented Oct 23 at 10:39
  • If I might ask, why does the difference between the code samples matter? It might help me understand the question better. Commented Oct 23 at 12:35
  • Re "I insist on saying thanks": and we all insist that you should stop doing that:) See meta.stackexchange.com/questions/2950/… At the very least, currently a TypedDict cannot be a subtype of a dict[A, B] for any A and B (maybe except for literal keys, but that still isn't allowed AFAIC). I doubt you can do this right now, but PEP728 (link to the relevant section) may change this situation when mypy implements it. Commented Oct 23 at 21:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.