2

I am trying to change the behavior of python's int class, but I'm not sure if it can be done using pure python. Here is what I tried so far:

import builtins
class int_new(builtins.int):
    def __eq__(self, other):
        return True
int = int_new
print(5 == 6) # the result is False, but I'm anticipating True
Mia
  • 2,466
  • 22
  • 38
  • Possible duplicate of [Override int()](https://stackoverflow.com/questions/11575393/overload-int-in-python) – AetherUnbound May 26 '17 at 15:31
  • Utterly impossible without recompiling Python - the creation of `int` objects from numeric literals happens at a far lower level than you can override. Also, 5 and 6 (and hundreds of other numbers) will already have been created as cached int objects before your program even starts running. – jasonharper May 26 '17 at 16:12
  • 1
    I'm curious why you would need to do this? What's your use case? – Marcel Wilson May 26 '17 at 21:11

2 Answers2

2

You should replace last line with:

print(int(5) == int(6))

to force/ask Python to use your new class for integer numbers.

davidedb
  • 867
  • 5
  • 12
  • I think that loses the point. If so, I can use any arbitrary classes and don't have to include `int=int_new` – Mia May 29 '17 at 18:03
  • The Python interpreter/syntax dictates how literals are interpreted. According to the syntax the literal `5` represent an instance of the builtin class `int` and this cannot be changed, unless you change the CPython source code. Therefore your only option to create instances of your special subclass is to tell Python explicitly to build them. – davidedb May 31 '17 at 07:19
-2

A year later I finally learned what I was wondering. When I was learning Python, I was not exposed to the idea of what a primitive type is. After learning C++ I realized that I was actually wondering if it is possible to replace primitive type with other custom types. The answer is obviously no.

Mia
  • 2,466
  • 22
  • 38
  • The problem is not that `int` is a primitive type, it's that the Python VM uses the built-in `int` as the type of `int` literals, and that there's no easy way to change this. – Ignacio Vazquez-Abrams Jul 22 '18 at 07:43
  • It is possible in python, you can import the ctypes module to change the value, but it's not a good thing to do, and will probably break other stuff – Alve Dec 18 '20 at 12:05