How does len work?

python

Solution

I don't think you can, unless you write your own len. The builtin len always return an int.

Problem

How does len work on Python? Look at this example: ``` class INT(int): pass class STR(str): def __len__(self): return INT(42) q = STR('how').__len__() print q, type(q) q = len(STR('how')) print q, type(q) ``` The output is: ``` 42 <class '__main__.INT'> 42 <type 'int'> ``` How can I handle it so len returns an INT instance? Answers suggest that the only solution is overriding len This is my alternative implementation. It doesn't seem very harmful. ``` original_len = len def len(o): l = o.__len__() if isinstance(l, int): return l original_len(o) ```

Original source