4 ms·
Non-CPython implementations may pass by value as an optimization for certain immutable builtin types. This is visible to code using `is`. (It's surprisingly di
by o11c 2y ago
Non-CPython implementations may pass by value as an optimization for certain immutable builtin types. This is visible to code using `is`.
(It's surprisingly difficult to implement a rigorous way to detect this vs compile-time constant evaluation though; note that identical objects of certain types are pooled already when generating/loading bytecode files. I don't think any current implementation is smart enough to optimize the following though)
$ python3 -c 'o = object(); print(id(o) is id(o))'
False
$ pypy3 -c 'o = object(); print(id(o) is id(o))'
True
$ jython -c 'o = object(); print(id(o) is id(o))'
True
- cwalv 2y agoAre you saying `o` is passed by value? I think this behavior is due to the return from `id()` being interned, or not. `id(o) == id(o)` will be true in all cases
- o11c 2y agoI mean that the `id` function returns by value. It's not interning since that explicitly refers to something allocated, which isn't the case here.
- ericvsmith 2y agoThis is incorrect. The returned integer is a regular Python object, not some "unboxed" integer value.
- ericvsmith 2y agoWhat you're seeing here is an optimization about integers, not about pass by value. CPython only does this for small integers: $ python -c "print(int('3') is int('3'))" True $ python -c "print(int('300') is int('300'))" False Other implementations make different choices.