简体   繁体   中英

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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM