4 ms·
So all Python numbers are objects and the implementation automatically pre-allocates and reuses instances for small numbers? What a strange implementation. I th
by matheusmoreira 7y ago
So all Python numbers are objects and the implementation automatically pre-allocates and reuses instances for small numbers? What a strange implementation. I thought it used tagged pointers like other dynamic languages. In Ruby, values can be pointers to objects but also 63 bit numbers when the least significant bit is set.
https://en.wikipedia.org/wiki/Tagged_pointer https://en.wikipedia.org/wiki/Tagged_pointer
This issue of object identity and equality isn't unique to Lisp but I agree that applying it to numbers produces unexpected results.
- pansa2 7y ago> I thought it used tagged pointers like other dynamic languages. No. IIRC tagged pointers were considered too complex to expose via Python’s C API.
- matheusmoreira 7y agoIn Ruby C extensions it works like this: int FIXNUM_P(VALUE object_pointer) { return object_pointer & 1; } long FIX2LONG(VALUE object_pointer) { return object_pointer >> 1; } VALUE ruby_value; long number; if (FIXNUM_P(ruby_value)) number = FIX2LONG(ruby_value); I thought this was pretty simple. What does Python's C API look like?
- __s 7y agohttps://mail.python.org/pipermail/python-dev/2004-July/046139.html https://mail.python.org/pipermail/python-dev/2004-July/04613... -1000 from GvR
- userbinator 7y agoHere's his actual reply: https://mail.python.org/pipermail/python-dev/2004-July/046147.html https://mail.python.org/pipermail/python-dev/2004-July/04614...
- jraph 7y agoJava does the same thing for small numbers.
- matheusmoreira 7y agoYeah, the Integer class maintains a cache of all signed 8 bit values: https://stackoverflow.com/a/3131208/512904 https://stackoverflow.com/a/3131208/512904 In Java, there's a clear distinction between a primitive int value and an Integer object. Not all languages have this property. I thought Python didn't.
- viraptor 7y agoIt applies to Ruby as well, just in different cases: irb(main):020:0> 10.0.__id__ => 81064793292668930 irb(main):021:0> 10.__id__ => 21 irb(main):022:0> 10==10.0 => true And for very large numbers: irb(main):031:0> 1e200.__id__ => 340 irb(main):032:0> 1e200.__id__ => 360 So it's a different threshold and different cases, but as a general rule, "equality and identity are different" still holds.
- matheusmoreira 7y agoYes. Floating point numbers cannot be folded into object pointers and are always copied into newly allocated objects. Integers larger than ((sizeof(long) * CHAR_BIT) - 1) will actually become an arbitrary precision integer object.