[Tutor] making len() and __len__ return a non-int

Albert-Jan Roskam fomcl at yahoo.com
Sun Sep 2 13:30:45 CEST 2012

If I implement __len__ in my own class, does it really have to return an int? Is there no way around this (other than modifying the source code of python itself ;-) It would be nice if len(Example(row, col)) would return a dictionary, or a two-tuple (see code below). The strange thing is that calling __len__ directly does work: Example(1, 2).__len__() returns the dictionary. I always thought len() was a convenient "shorthand" for __len__. I've even been reading about metaclasses (interesting, dark, mysterious), thinking the answer might lie there. Note that my question is not whether it's a good idea to do this, I just find it interesting to understand how it could be done.

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
>>> class Example(object):
 def __init__(self, row, col):
  self.row = row
  self.col = col
 def __len__(self):
  return {self.row: self.col}
 >>> len(Example(1, 2))
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    len(Example(1, 2))
TypeError: an integer is required
>>> Example(1, 2).__len__()
{1: 2}


All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120902/8a2051cb/attachment.html>

More information about the Tutor mailing list