alonisser
alonisser

Reputation: 12088

problem with implenting __len__ with sqlalchemy func.count getting some kind of recursion error

the code - supposed to implent the len magic method with the following code:

    def __len__(self):

    from sqlalchemy import func
    self.len = session.query(func.count(Question.id)).scalar()
    return int(self.len)

def __repr__(self):

    self.repr = "traffic theory question, current number of questions:{0}".format(self.__len__)
    return self.repr

what I get (the 3 upper lines keep on repeating in a long list and then terminate with the following line):

  File "C:\Python27\dir\file.py", line 129, in __repr__
    self.repr = "traffic theory question, current number of questions:{0}".format(self.__len__)
RuntimeError: maximum recursion depth exceeded while getting the str of an object

I should stress I'm getting this error only when calling the repr class method but when I call len(q) (q is the class instance i'm working with) I get the right answer!

any clues?

Upvotes: 0

Views: 403

Answers (1)

agf
agf

Reputation: 176930

You're trying to format an instance method, self.__len__, not the length returned by that instance method.

When you try to format(self.__len__), it calls repr on the instance referred to by self, creating the recursion.

You need to use format on self.__len__() (or len(self) or self.len).

Upvotes: 2

Related Questions