pc3e
pc3e

Reputation: 1369

"object cannot be interpreted as an integer"

I have a library with a function that used to return an integer, but will now instead return an object of a "field" class I defined. I wanted this class to behave as close to an integer as possible to maintain compatibility with scripts that use this library, although I couldn't extend int since the value needs to be mutable. So I defined __int__(), __add__(), __radd__() and so on, hoping that nobody would even notice that the function no longer returns a regular integer. However, this didn't turn out as I planned, as several built-in functions will now raise "TypeError: 'field' object cannot be interpreted as an integer". (Such as hex().) Is there anything I can do about this, so that my class can be "interpreted as an integer"?

To anyone wondering why this change was necessary, the function I mentioned is the __getitem__() function of another class ("block") that represents a collection of these "fields". Objects of "block" are used as the locals argument for eval() to evaluate expressions such as field1 + field2 and I wanted it to be possible to use other properties of the fields in these expressions.

Upvotes: 3

Views: 10712

Answers (1)

martineau
martineau

Reputation: 123463

Adding an __index__(self) method and returning the int (or long) value contained in your field class should make it acceptable to many of Python's built-ins.

Upvotes: 6

Related Questions