Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Pythons builtin type with custom one

Is it possible to replace some built-in python types with custom ones?

I want to create something like:

class MyInt(object):
   ...
__builtin__.int = MyInt
x = 5
like image 351
Wojciech Danilo Avatar asked Feb 20 '23 16:02

Wojciech Danilo


1 Answers

You seem to be asking if it's possible to override the type that is created when you enter literals. The answer is no. You cannot make it so that x = 5 uses a type other than the built-in int type.

You can override __builtin__.int, but that will only affect explicit use of the name int, e.g., when you do int("5"). There's little point to doing this; it's better to just use your regular class and do MyInt("5").

More importantly, you can provide operator overloading on your classes so that, for instance, MyInt(5) + 5 works and returns another MyInt. You'd do this by writing an __add__ method for your MyInt class (along with __sub__ for subtraction, etc.).

like image 66
BrenBarn Avatar answered Apr 29 '23 16:04

BrenBarn