Python dataclass AttributeError

Question:

I have a dataclass set up like this:

from dataclasses import dataclass, field
from typing import List

@dataclass
class stats:
    target_list: List[None] = field(default_factory=list)

When I try to compare the contents of the list like so:

if stats.target_list == None:
    pass

I get AttributeError: type object ‘stats’ has no attribute ‘target_list’

How can I fix this issue? Thanks

Asked By: Mato098

||

Answers:

You’re trying to find an attribute named target_list on the class itself. You want to testing an object of that class. For example:

from dataclasses import dataclass, field
from typing import List

@dataclass
class stats:
    target_list: List[None] = field(default_factory=list)


def check_target(s):
    if s.target_list is None:
        print('No target list!')
    else:
        print(f'{len(s.target_list)} targets')


StatsObject1 = stats()
StatsObject2 = stats(target_list=['a', 'b', 'c'])

check_target(StatsObject1)
check_target(StatsObject2)

Answered By: larsks
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.