Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class or static method as default_factory in dataclasses

I want to populate an attribute of a dataclass using the default_factory method. However, since the factory method is only meaningful in the context of this specific class, I want to keep it inside the class (e.g. as a static or class method). For example:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Deck:
    cards: List[str] = field(default_factory=self.create_cards)

    @staticmethod
    def create_cards():
        return ['King', 'Queen']

However, I get this error (as expected) on line 6:

NameError: name 'self' is not defined

How can I overcome this issue? I don't want to move the create_cards() method out of the class.

like image 448
Kurt Bourbaki Avatar asked Mar 10 '26 23:03

Kurt Bourbaki


1 Answers

One possible solution is to move it to __post_init__(self). For example:

@dataclass
class Deck:
    cards: List[str] = field(default_factory=list)

    def __post_init__(self):
        if not self.cards:
            self.cards = self.create_cards()

    def create_cards(self):
        return ['King', 'Queen']

Output:

d1 = Deck()
print(d1) # prints Deck(cards=['King', 'Queen'])
d2 = Deck(["Captain"])
print(d2) # prints Deck(cards=['Captain'])
like image 174
momo Avatar answered Mar 12 '26 11:03

momo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!