Sachin Dev Sharma
Sachin Dev Sharma

Reputation: 221

if else in Python dataclasses

I'm trying to put if else with dataclass. Below is the code snippet.

from dataclasses import dataclass, field
@dataclass
class XYZ:
    test:bool = True
    if test:
        param:str = field(default='abcd', init=True)
    else:
        param:str = field(default='xyz', init=True)
    
    def f1(self):
        print(self.test, self.param)

if I run the above code as: XYZ(test=False).f1()

output is : False abcd

What I require is output to be False xyz

What am I missing here. Thanks in advance for the help.

Upvotes: 0

Views: 2448

Answers (1)

MatsLindh
MatsLindh

Reputation: 52832

You can't do conditional initializers in the class definition for objects, but you can use __post_init__ with a data class to modify or change property values after the object has been initialized:

from dataclasses import dataclass, field

@dataclass
class XYZ:
    test: bool = True
    param: str = None
    
    def __post_init__(self):
        if self.param is None:
            self.param = 'abcd' if self.test else 'xyz'
        
    def f1(self):
        print(self.test, self.param)
        
# Prints False, xyz            
XYZ(test=False).f1()

# Prints True, abcd
XYZ(test=True).f1()

# Prints True, foo
XYZ(test=True, param='foo').f1()

This should match the behavior you described.

Upvotes: 3

Related Questions