6

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

Mato098
  • 65
  • 1
  • 4
  • 1
    Try `stats().target_list` - apparently only an instance has that attribute. – wwii Jan 25 '21 at 20:07
  • after doing so its first problem was that some attributes do not have value (such as `Something: float`), and after assigning something to all attributes, the same error appears – Mato098 Jan 25 '21 at 20:13
  • Edit: your solution works as well, I just had the same call few lines down and didn't change it while trying your solution – Mato098 Jan 25 '21 at 20:21

1 Answers1

5

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)

larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    Note that you should be using `is` instead of `==` to test for `None`, and also that `target_list` will never be `None` (if unset, it will be an empty list). I've updated the example in my answer to be a bit more complete. – larsks Jan 25 '21 at 20:18