mardi 19 avril 2022

Pattern for multistep initialization

I'm writing a class that gets initialized in multiple steps. I don't like the resulting code, and I'm looking for a pattern that would make it cleaner.

Here is an example to illustrate what I mean by initialization in multiple steps.

Say I have a class for an object that will read two streams of data: numbers and operations. Before it consumes at least one element of the operations stream it does not know what to do with the numbers so it drops them. Like this:

class OpNumbers:

    def __init__(self):
        self.op = None

    def process_op(self, op):
        self.op = op

    def process_number(self, number):
        if self.op is not None:
            print(self.op(number))
        else:
            print('dropping', number)

I call this multistep initialization, as the class is initialized twice, one time with the __init__ method when creating an object, and second time when I observe the first op.

The part I don't like is this constant checking if self.op is None. In this code it doesn't look too bad, but in my code which is more complex, tracking the state of the second initialization gets really annoying.

Aucun commentaire:

Enregistrer un commentaire