user972014
user972014

Reputation: 3856

passing dataclass as default parameter

I have some dataclass with default values:

@dataclasses.dataclass
class SomeDataclass:
    field: str = ""
    number: int = 3

I have a function that receives that as a parameter. I want to enable it to receive empty parameter, which will cause it to instantiate a default dataclass. This is the behavior I want:

def func(instance: SomeDataClass = None):
    # I want to get rid of these lines
    if instance is None:
        instance = SomeDataClass()

Is that possible somehow without explicitly doing it?

Upvotes: 0

Views: 882

Answers (2)

balderman
balderman

Reputation: 23815

Another option is to define the class on the fly an instantiate it on the fly as well.

The main issue here is that we define the class twice.

So I dont think its the way to go until we can have a way to define the class only once.

from dataclasses import dataclass,field
import dataclasses

@dataclass
class SomeDataClass:
    f: str = 'jack'
    number: int = 12
                   

def foo(data=dataclasses.make_dataclass('SomeDataClass',[('f',str,field(default='jack')),('number', int,field(default=12))])()):
  print(data)

foo()
foo(SomeDataClass('jim',33))

output

SomeDataClass(f='jack', number=12)
SomeDataClass(f='jim', number=33)

Upvotes: 0

chepner
chepner

Reputation: 531125

If the function will not modify the instance of SomeDataclass, you can safely use

def func(instance: SomeDataClass = SomeDataclass()):
    ...

The check-for-None idiom is used when each call to the function should gets its own, new instance of a mutable value (like a list, dict, or set).

Otherwise, no: you need a sentinel to indicate whether or not func should instantiate SomeDataclass itself.

Upvotes: 2

Related Questions