2

I define a NE_Conv2d class and override its __getattr__. When I try to get an existing attribute from one instance of this class, __getattr__ is called and enter infinite recursion.

I know one need to deal with __getattr__ carefully to avoid infinite recursion, but apparently the conv attribute already exists after __init__ is called. So when I try to get conv attribute, __getattr__ should not be called.

from torch import nn
class NE_Conv2d(nn.Module):
    '''Nonexpansive conv2d'''

    def __init__(self, *k, **kw):
        super(NE_Conv2d, self).__init__()
        self.conv = nn.Conv2d(*k, **kw)
        print('foo')

    def __getattr__(self, attr):
        return getattr(self.conv, attr)

a = NE_Conv2d(3, 32, 5)
print(a)
print(a.conv)

Above code should print info about a and a.conv, but enter infinite recursion when trying to get a.conv.

2
  • __getattr__ is only called if an attribute (conv here) is not found on an object. In this case self.conv is assigned in the __init__ method so __getattr__ will not be called if a.conv is accessed. Commented Jun 8, 2019 at 7:45
  • My thought is same as yours and that's the reason why I am totally confused when I run the above code and got RecursionError: maximum recursion depth exceeded error. Commented Jun 8, 2019 at 8:01

1 Answer 1

0

I seem to know what's wrong... setattr and getattr of nn.Module is reloaded...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.