Is there a way that you can redefine built-in classes in python (eg int). When I just do class int
then the type is __main__.int
not int
, is there any way to define it without the __main__
?
Asked
Active
Viewed 77 times
-1

THEWHY
- 1
- 5
-
2What would you want the effect of this to be? – kaya3 Dec 22 '21 at 22:01
-
3Sure, you can do `int = float`, but what's the point? This seems to be a so-called "xy problem". In other words, you're asking the wrong question. – Ulrich Eckhardt Dec 22 '21 at 22:02
-
I don't really know, I was just wondering if there was any way to do it, possibly being able to edit how two ints interact, like changing what + or - do to two numbers – THEWHY Dec 22 '21 at 22:02
-
Much of that is compiled into the interpreter, so you can't change it. – Barmar Dec 22 '21 at 22:04
-
[how-to-properly-overload-the-add-method](https://stackoverflow.com/questions/36785417/how-to-properly-overload-the-add-method) for classes that want an "add-like" functionality – Patrick Artner Dec 22 '21 at 22:04
-
@PatrickArtner That's for adding the method to user-defined classes, not changing how built-in classes work. – Barmar Dec 22 '21 at 22:05
-
@Barmar hence the _for classes that want an "add-like" functionality_ ... – Patrick Artner Dec 22 '21 at 22:07
-
I tried to overload the built-in `__radd__` function of int and it raised this error: `TypeError: can't set attributes of built-in/extension type 'int'` It looks like they have custom exceptions for when someone attempts to do something like this. – Ryan Nygard Dec 22 '21 at 22:09
-
@Barmar [never say never](https://github.com/clarete/forbiddenfruit). It is *possible*, although, IMO, highly highly inadvisable. – juanpa.arrivillaga Dec 22 '21 at 22:10
-
1@RyanNygard you mean *assign to*, not overload. But yeah, dynamically modifying built-in classes is not supported. Although it is possible if you are willing to play around knowing the implementations details and other black magics. – juanpa.arrivillaga Dec 22 '21 at 22:11
-
This should probably be a dupilcate of: https://stackoverflow.com/questions/192649/can-you-monkey-patch-methods-on-core-types-in-python – juanpa.arrivillaga Dec 22 '21 at 22:45
-
@juanpa.arrivillaga Which presumably means it will be implementation-dependent changes, not portable. – Barmar Dec 22 '21 at 23:44
1 Answers
0
i don't think thats possible without editing python source written in c
but you can inherit from the built in classes like int
then add your methods like:
class MyList(list):
def sumOfAll(self):
return sum(self)
myList = MyList([1,2,3])
print(myList.sumOfAll())
Output : 6

Ahmad
- 119
- 4
-
Ok, I was assuming it wasn't possible but just wanted to check, thanks for clarifying. – THEWHY Dec 22 '21 at 22:09
-
1It is *possible* without editing the source, but not advisable. – juanpa.arrivillaga Dec 22 '21 at 22:12