Initializing python dataclass object without passing instance variables or default values
Asked Answered
M

2

6

I want to initialize python dataclass object even if no instance variables are passed into it and we have not added default values to the param

@dataclass
class TestClass:
   
   paramA: str
   paramB: float
   paramC: str

obj1 = TestClass(paramA="something", paramB=12.3)

Here it won't allow me to create the object & it will throw

TypeError: __init__() missing 1 required positional argument: 'paramC'

I can use the default value to resolve this error.

paramC: str = None
# OR
paramC: str = ""

But I don't want to use a default value for paramC because I want a scenario such that if we pass paramC then only it should be there in the object else it should not be there. So if we use default value here paramC will always be there in the object with value None OR empty string.

I would like to skip initialization of a param if it is not passed during initialization.

Melgar answered 6/3, 2022 at 8:44 Comment(7)
You shouldn't use dataclass for your scenario. Either way, why do you want it to not exist? It is unexpectedGavin
It's a business usecase wherein sometimes we will receive the data which contains that param & sometimes it won't be there so I want to have that flexibility along with other characteristics that dataclass provides.Melgar
And why not default it to None, or any other sentinel?Gavin
If we do that then whenever we will try to print the object or use it as a dict the param will be shown with val as None. And if we try to override other private methods then we can create a skmpla python class without using dataclass as it doesn't matter thenMelgar
dataclass is not meant for this. It is meant to create expected normal objects with all of the attributes, that's why the feature isn't even implemented. Avoiding the need to "print" the optional fields should be handled solely with the __repr__ method.Gavin
So there is no workaround that might be possible here?Melgar
You're forcing it by using a dataclass against the way dataclasses work. You can create an init-only field, but I don't suggest doing it whatsoever as I'm not entirely sure it'll even solve your problem.Gavin
A
0

I think you may want something like this answer

Which uses make_dataclass to create an object on the fly

Alcibiades answered 18/8, 2023 at 20:57 Comment(0)
A
-3

You can use Optional typing.

from typing import Optional

@dataclass
class TestClass:
   
   paramA: str
   paramB: float
   paramC: Optional[str] = None

obj1 = TestClass(paramA="something", paramB=12.3)
Avon answered 9/9, 2022 at 13:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.