[Python] Is there a way to get a Python dataclass length?

Discussão em 'Python' iniciado por Stack, Agosto 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataclass for a set of timers. Each instance of the dataclass can have a different number of times. The number of timers in a specific instance is fixed but can vary between instances. I'd like to get the number of timers in a specific class using __len__. How can I specify the return value of __len__ with out resorting to a magic number like in my demo code? I'd rather it be generated programmatically when __len__ is called so there's no possibility of a maintenance error.

    Here's my code:

    @dataclass
    class SSTimers():

    def tic(self):
    pass

    def __iter__(self):
    return iter([])

    @dataclass
    class Timers(SSTimers):
    intervalTimer = tmr.Timer(0)
    vSafetyPTimer = tmr.Timer(0)
    aRefractoryTimer = tmr.Timer(0)
    aBlankingTimer = tmr.Timer(0)
    vRefractoryTimer = tmr.Timer(0)
    vBlankingTimer = tmr.Timer(0)

    def tic(self):
    self.intervalTimer.tic()
    self.vSafetyPTimer.tic()
    self.aRefractoryTimer.tic()
    self.aBlankingTimer.tic()
    self.vRefractoryTimer.tic()
    self.vBlankingTimer.tic()

    def __len__(self):
    return 6

    def __iter__(self):
    return iter([self.intervalTimer, self.vSafetyPTimer, self.aRefractoryTimer, self.aBlankingTimer, self.vRefractoryTimer, self.vBlankingTimer ])



    I'd like len to return something like len(__iter__) if that makes any sense.

    Continue reading...

Compartilhe esta Página