Search code examples
pythonpython-dataclasses

How to get number of attributes in a dataclass?


I want to get the number of recipes I have in the Recipes class. How do I go about doing this?

from dataclasses import dataclass

@dataclass
class Recipe:
    ing1: str
    ing2: str
    ing3: str
   
class Recipes():
    pass
   
setattr(Recipes, 'Salad', Recipe('cabbage', 'lettuce', 'potato')
setattr(Recipes, 'Salad2', Recipe('tomato', 'lettuce', 'ranch')
print("There are %s number of recipes!" % # thing that gets number of attributes here #)
# prints 2

This is what I have so far. I want the thing at the end to print the number of recipes in the class (currently being 2).

Edit: I can't use dict or lists because this is just a test for something I am working on.


Solution

  • You can traverse Recipes.__dict__ to count all entries of type Recipe. This dict contains all set attributes and few other entries.

    Try it online!

    from dataclasses import dataclass
    
    @dataclass
    class Recipe:
        ing1: str
        ing2: str
        ing3: str
       
    class Recipes():
        pass
       
    setattr(Recipes, 'Salad', Recipe('cabbage', 'lettuce', 'potato'))
    setattr(Recipes, 'Salad2', Recipe('tomato', 'lettuce', 'ranch'))
    
    cnt = 0
    for k, v in Recipes.__dict__.items():
        if type(v) is Recipe:
            cnt += 1
    
    print(f"There are {cnt} number of recipes!")
    

    Output:

    There are 2 number of recipes!