Search code examples
pythonpython-dataclasses

Python dataclass AttributeError


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


Solution

  • 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)