Eli Korvigo
Eli Korvigo

Reputation: 10483

super().__init__ overwrites an attribute

I'm setting an attribute in a subclass initialiser, which seems to be overwritten by a call to super().__init__.

from keras.layers import GRU, wrappers


class Dummy(wrappers.Wrapper):
    def __init__(self, layer, **kwargs):
        self.stateful = True
        print(self.stateful)
        super().__init__(layer, **kwargs)
        print(self.stateful)

In [3]: dummy = Dummy(GRU(64, stateful=True))
True
False
In [4]: dummy.stateful
Out[4]: False

I would assume something in wrappers.Wrapper overwrites the attribute, but a built-in wrapper subclass Bidirectional with an almost identical superclass init call (I basically followed the pattern from this subclass in my implementation)

class Bidirectional(Wrapper):

    def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):
        ...
        self.stateful = layer.stateful
        ...
        super(Bidirectional, self).__init__(layer, **kwargs)

doesn't demonstrate this behaviour

In [6]: bidir = wrappers.Bidirectional(GRU(64, stateful=True))

In [7]: bidir.stateful
Out[7]: True

I can't wrap my head around this. I'm using Keras 2.1.3 under Python 3.6.

P.S.

I've already tried replacing super().__init__(layer, **kwargs) with super(Dummy, self).__init__(layer, **kwargs) in my subclass to no avail.

Upvotes: 1

Views: 517

Answers (1)

user2357112
user2357112

Reputation: 280237

You're looking at the wrong version of the Bidirectional source code. The version you're looking at seems to be this one, from three days ago. I believe that version has the same bug your code has.

The code in what I believe is the latest release calls super().__init__ at the start of its own __init__:

def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):
    super(Bidirectional, self).__init__(layer, **kwargs)
    ...

That way, its actions happen after the ancestor constructors' actions, and its assignment of self.stateful overrides its ancestors.

Upvotes: 2

Related Questions