Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values for TypedDict

Let's consider I have the following TypedDict:

class A(TypedDict):
    a: int
    b: int

What is the best practice for setting default values for this class?

I tried to add a constructor but it doesn't seem to work.

class A(TypedDict):
    a: int
    b: int
    def __init__(self):
        TypedDict.__init__(self)
        a = 0
        b = 1

EDIT: I don't want to use dataclass because I need to serialize and deserialize to JSON files and dataclasses have some problem with it.

What do you think?

like image 462
Gil Ben David Avatar asked Feb 20 '26 08:02

Gil Ben David


1 Answers

TypedDict is only for specifying that a dict follows a certain layout, not an actual class. You can of course use a TypedDict to create an instance of that specific layout but it doesn't come with defaults.

One possible solution is to add a factory method to the class. You could use this factory method instead to set defaults.

from typing import TypedDict

class A(TypedDict):
    a: int
    b: int

    @classmethod
    def create(cls, a: int = 0, b: int = 1) -> A:
        return A(a=a, b=b)

a = A.create(a=4)
# {"a": 4, "b": 1}

If having a dict is not a strict requirement then @dataclass is good having small objects with defaults.

from dataclasses import dataclass

@dataclass
class A:
    a: int = 0
    b: int = 1

If you need to create a dictionary from them, you can use asdict

from dataclasses import asdict

a = A(a=4)
asdict(a)  # {"a": 4, "b": 1}
like image 146
Eddie Bergman Avatar answered Feb 22 '26 22:02

Eddie Bergman