Passing default list argument to dataclasses

前端 未结 2 628
离开以前
离开以前 2020-12-05 10:54

I would like to pass default argument in my class, but somehow I am having problem:

from dataclasses import dataclass, field
from typing import List

@datac         


        
相关标签:
2条回答
  • 2020-12-05 11:08

    For complex datatypes i tend to abbreviate like so:

    import copy
    from dataclasses import dataclass, field
    from typing import Dict, Tuple
    
    def default_field(obj):
        return field(default_factory=lambda: copy.copy(obj))
    
    @dataclass
    class C:
        complex_attribute: Dict[str, Tuple[int, str]] = default_field({"a": (1, "x"), "b": (1, "y")})
    
    0 讨论(0)
  • 2020-12-05 11:19

    From the dataclasses.field docs:

    The parameters to field() are:

    • default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory.

    Your default_factory is not a 0-argument callable but a list, which is the reason for the error:

    @dataclass
    class Pizza():
        ingredients: List = field(default_factory=['dow', 'tomatoes'])  # <- wrong!
    

    Use a lambda function instead:

    @dataclass
    class Pizza():
        ingredients: List = field(default_factory=lambda: ['dow', 'tomatoes'])
    
    0 讨论(0)
提交回复
热议问题