Initializing python dataclass object without passing instance variables or default values

Viewed 1842

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.

1 Answers

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)
Related