TypeError during using python dataclass

234 views Asked by At
@dataclass
class cntr(setup):
    source:str = 'S2'
    vi:str = 'SW'
    # Dataframe containing information on samples
    df:pd.DataFrame = pd.DataFrame()

    # Available bands
    bands:List[str] = field(default_factory=[])

    indices:List[str] = [vi] + bands

In the code above, I get this error for the line indices:List[str] = [vi] + bands:

*** TypeError: can only concatenate list (not "Field") to list

How do I fix this?

1

There are 1 answers

0
FlorianGD On BEST ANSWER

You can define indices in __post_init__. It will not appear in the repr but it will be accessible as a property.

You also need to have a callable for default_factory, so list instead of [] .

Here is a simplified example (as I do not know what is setup:

@dataclass
class cntr():
    source:str = 'S2'
    vi:str = 'SW'
    # Available bands
    bands:List[str] = field(default_factory=list)

    def __post_init__(self):
        self.indices:List[str] = [self.vi] + self.bands
c = cntr()
c.indices  # will print: ['SW']