Maximum recursion depth error with getattr
Asked Answered
A

1

2

I have this code;

class NumberDescriptor(object):
    def __get__(self, instance, owner):
        name = (hasattr(self, "name") and self.name)
        if not name:
            name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
            self.name = name
        return getattr(instance, '_' + name)
    def __set__(self,instance, value):
        name = (hasattr(self, "name") and self.name)
        if not name:
            owner = type(instance)
            name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]
            self.name = name
        setattr(instance, '_' + name, int(value))

class Insan(object):
    yas = NumberDescriptor()

a = Insan()
print a.yas
a.yas = "osman"
print a.yas

I am getting maximum recursion depth error in the line name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0]. I want that line to get me the name of variable used for current descriptor instance. Can anyone see what am I doing wrong here?

Alisun answered 28/8, 2012 at 16:20 Comment(0)
C
11

The getattr() call is calling your __get__.

One way to work around this is to explicitly call through the superclass, object:

object.__getattribute__(instance, name)

Or, clearer:

instance.__dict__[name]
Cirone answered 28/8, 2012 at 16:27 Comment(1)
instance.__dict__[name] might fail for non-data descriptors in general case. NumberDescriptor is a data descriptor so it should work in this case.Mclain

© 2022 - 2024 — McMap. All rights reserved.