Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are numbers represented as objects in python?

Every time I perform an arthetic operation in python, new number objects are created. Wouldn't it be more efficient for the interpreter to perform arithmetic operations with primitive data types rather than having the overhead of creating objects (even for numbers) for arithmetic operations? Thank you in advance

like image 642
ben bitdiddle Avatar asked Sep 12 '25 06:09

ben bitdiddle


2 Answers

Yes, it would.

Just like contrived benchmarks prove more or less whatever you want them to prove.

What happens when you add 3 + 23431827340987123049712093874192376491287364912873641298374190234691283764? Well, if you're using primitive types you get all kinds of overflows. If you're using Python objects then it does some long maths, which yeah, is slower than native math, but they're big numbers so you kind of have to deal with that.

like image 104
Wayne Werner Avatar answered Sep 14 '25 21:09

Wayne Werner


Your right, when you use objects, you have a small overhead which deteriorates efficiency.

But numbers are non-mutable and memory allocation is optimized for small numbers: see the article Python integer objects implementation.

Using objects allows the developer to inherit the number classes int, float, complex and add new, specialized methods.

In Python, a type Hierarchy for Numbers is also defined: Number :> Complex :> Real :> Rational :> Integral. That way, you can have features similar to Scheme.

If you need optimization, you can use Cython. It uses the C language to perform optimizations.

On the other hand, you also have the famous NumPy for scientific computing with Python. This library is also compiled in C.

If you really want to play with primitive types, there is an array standard packages: Efficient arrays of numeric values.

As a conclusion: We agree that Python numbers are not primitive types, but using objects offer many more possibilities without introducing complexity for the developer, and without too much lose of performance.

like image 39
Laurent LAPORTE Avatar answered Sep 14 '25 19:09

Laurent LAPORTE