#๐Ÿ”’ Typehint classes with TypedDict

25 messages ยท Page 1 of 1 (latest)

halcyon mesa
#

I have a class inheriting dict: py class MyDict(dict): ... and a Typehint defined:py class MyDictTypeHint(TypedDict): key1: int key2: str How do I typehint MyDict to MyDictTypeHint? I tried inheriting from both:```py
class MyDict(dict, MyDictTypehint):
...

cunning pineBOT
#

@halcyon mesa

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

main kraken
#

what are you actually trying to accomplish by subclassing dict?

#

the usual way is to just use the TypedDict subclass

halcyon mesa
main kraken
#

ok, why not just add those to your TypedDict subclass then?

halcyon mesa
main kraken
#

TypedDict is also a dict

#

have you at least tried to do this?

halcyon mesa
#

yup, I made a shorter example tho its not same

#

!e

from typing import TypedDict

class MyTypedDict(TypedDict):
    key1: int
    
class MyDict(MyTypedDict):
    
    def __init__(self, value):
        super().__init__({
            'key1': value - 10
        })

foo = MyDict(20)
print(foo)
cunning pineBOT
halcyon mesa
main kraken
#

that is an odd way to use dicts

#

why is your class a dict subclass at all?

#

if you insist on doing this, then you need to override __new__() instead of __init__()

halcyon mesa
#

let me try

halcyon mesa
main kraken
#

are you otherwise using tMyDict as a dict? like you're using other dict methods too?

#

if not, then maybe implementing __getitem__() would be enough

halcyon mesa
halcyon mesa
main kraken
#

WDYM?

cunning pineBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.