Unexpected Output with Default parameters

This sample code here produces an output waveform which is same for both the signals ‘sig’ of the instances ‘a’ and ‘b’.
This happens only when I use the default parameter(In this example value for ‘sig’ is not passed when class object is created, instead the default value is used).
The problem can be avoided by passing two different Signal variables(instead of using the default value) when the class object is created.
Can someone tell me whether this is a problem with MyHDL or python or the way I coded?
Maybe this is inevitable and I should not use default signal values?

I tried this:

class Test:

    def __init__(self, clock, sig=None):

        self.clock = clock
        self.sig = sig if sig is not None else Signal(bool(0))


    def process(self, i):

        @always(self.clock.posedge)
        def test():
            if i :
                self.sig.next = not self.sig
        return test

and then got the expected result.

Ok, thanks. So, I have to change the way I code !

But do you know why? Think about it for a while …

Yeah, now I understand. Function’s default arguments can only be immutable(whereas Signal(bool(0)) is mutable), because they are assigned during function definition and not during every function call.

Not the right answer. The simulation showed that both but a.sig and b.sig changed because …

Since mutable type is used as default argument. In all the instances of the class, ‘sig’ will be referencing the same object. So when a.sig was changed b.sig also changed and vice versa.

That makes an ‘S’. :slight_smile:

Thank you :slight_smile: