Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the __int__ and __index__ methods in Python 3?

Tags:

python

casting

The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods:

object.__int__(self)

Called to implement the built-in [function int()]. Should return [an integer].

object.__index__(self)

Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). Must return an integer.

I understand that they're used for different purposes, but I've been unable to figure out why two different methods are necessary. What is the difference between these methods? Is it safe to just alias __index__ = __int__ in my classes?

like image 262
Jeremy Avatar asked Sep 02 '25 04:09

Jeremy


2 Answers

See PEP 357: Allowing Any Object to be Used for Slicing.

The nb_int method is used for coercion and so means something fundamentally different than what is requested here. This PEP proposes a method for something that can already be thought of as an integer communicate that information to Python when it needs an integer. The biggest example of why using nb_int would be a bad thing is that float objects already define the nb_int method, but float objects should not be used as indexes in a sequence.

Edit: It seems that it was implemented in Python 2.5.

like image 153
Alok Singhal Avatar answered Sep 04 '25 19:09

Alok Singhal


I believe you'll find the answer in PEP 357, which has this abstract:

This PEP proposes adding an nb_index slot in PyNumberMethods and an __index__ special method so that arbitrary objects can be used whenever integers are explicitly needed in Python, such as in slice syntax (from which the slot gets its name).

like image 22
Peter Hansen Avatar answered Sep 04 '25 19:09

Peter Hansen