Why are numbers represented as objects in python?

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

+3


source to share


2 answers


Yes, it would be.

Just like contrived tests prove more or less what you want them to prove.



What happens if you add 3 + 23431827340987123049712093874192376491287364912873641298374190234691283764? Well, if you use primitive types, you get all kinds of overflows. If you are using Python objects, then it does some long math calculations, which are yes, slower than native math, but they are big numbers, so you have to deal with that.

+4


source


Your right, when you use objects, you have a small overhead that degrades efficiency.

But the numbers don't change, and memory allocation is optimized for small numbers: see Python Integer Implementation .

Using objects allows developers to inherit the numeric classes int

, float

, complex

and to add new specialized techniques.

Python also defines the type of hierarchy for numbers : Number:> Complex:> Real:> Rational:> Integral. This way you can have Scheme-like functionality.



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

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

If you really want to play with primitive types, there are array

standard packages: efficient arrays of numeric values.

In conclusion: We agree that Python numbers are not primitive types, but using objects provides a lot more power without introducing developer complexity and losing too much performance.

+2


source







All Articles