Python property getter and setter with nn.Module

In the code below, I’m using property getter and setter to assign a Module (SubNet) to an attribute of another Module (Network). It seems that the setter of Network is not called. Not like I must write the code in this way, but I’m wondering why this is prevent.

import torch.nn as nn

class Network(nn.Module):
    def __init__(self):
        super(Network, self).__init__()
        self._sub_net = None

    @property
    def sub_net(self):
        print("getter")
        return self._sub_net

    @sub_net.setter
    def sub_net(self, net):
        print("setter")
        self._sub_net = net

class SubNet(nn.Module):
    def __init__(self):
        super(SubNet, self).__init__()
        pass

class Object(object):
    def __init__(self):
        super(Object, self).__init__()
        pass

ss = Network()
ss.sub_net = SubNet() # this prints nothing
# ss.sub_net = Object() # this prints "setter"
1 Like

Is stumbled upon the same issue and found an answer here on Stack Overflow:

As far as I understand this is the basic cause: Since nn.Module implements a __settatr__() method that doesn’t call the builtin __settattr__ in the case that the attribute you try to set is a itself a nn.Module the property setter is never executed. For other attributes that are not some PyTorch specific types (check the implementation for details: pytorch/module.py at eab59bae15bda508cdfbbc69a1a761b2b2c3780b · pytorch/pytorch · GitHub) the setter should work as usual.