Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python dataclass default factory

from dataclasses import dataclass, field

@dataclass
class Fruits():
    # names : list = []  # ValueError: mutable default <class 'list'> for field names is not allowed: use default_factory
    names : list = field(default_factory=lambda : [])


f1 = Fruits()
f1.names.append('Apple')
f1.names.append('Banana')
print(f1)      # Fruits(names=['Apple', 'Banana'])


f2 = Fruits(['Peach', 'Pear'])
print(f2)      # Fruits(names=['Peach', 'Pear'])
Source by code-maven.com #
 
PREVIOUS NEXT
Tagged: #python #dataclass #default #factory
ADD COMMENT
Topic
Name
1+6 =