[Python-ideas] Dunder method to make object str-like

Eric V. Smith eric at trueblade.com
Thu Apr 7 20:09:12 EDT 2016


On 4/7/2016 3:00 PM, Chris Barker wrote:
> On Thu, Apr 7, 2016 at 11:59 AM, Ethan Furman <ethan at stoneleaf.us
> <mailto:ethan at stoneleaf.us>> wrote:
> 
>     __index__ was originally created to support indexing, but has
>     morphed over time to mean "something that can be losslessly
>     converted to an integer".
> 
> 
> Ahh! very good precedent, then -- where else is this used?

It's used by hex, oct, and bin, at least:

>>> class Foo:
...   def __index__(self): return 42
...
>>> hex(Foo())
'0x2a'
>>> oct(Foo())
'0o52'
>>> bin(Foo())
'0b101010'
>>>



More information about the Python-ideas mailing list