[Python-Dev] ctypes: is it intentional that id() is the only way to get the address of an object?
On Fri, 18 Jan 2019 at 09:52, Steven D'Aprano <steve at pearwood.info> wrote:
> Code-wise, I'm not doing anything with ctypes.
> Language-wise, I'm trying to get a definitive answer of whether or not
> id() returning the address of the object should be a guaranteed feature
> or not.
> Across the entire Python ecosystem, no it isn't, as Jython and
> IronPython return consecutive integers. But should we consider it an
> intentional part of the CPython API?
> There are developers who insist that when it comes to CPython, id()
> returning the object address is an intentional feature that they can and
> do rely on, because (so I was told by one of them) that using id() is
> the only way to get the address of an object from pure-Python.
> According to this claim, using id() to get the address for use in ctypes
> is the correct and only way to do it, and this is a deliberate design
> choice by the core devs rather than an accident of the implementation.
> So long as you know you are using CPython, this is (so I was told)
> completely safe.
> In the grand scheme of things this may be a pretty minor issue. But I
> suspect that it could be a pain point for implementations like PyPy that
> support both objects that move and a ctypes emulation.
As per Eryk Sun's reply, the "correct" way to get an object address is
by using ctypes.py_object.
Supporting py_object may be a pain point for other implementations
that emulate ctypes, but then again, so is supporting the whole
CPython C API (which is where the py_object type is needed, so it's
basically the same problem).
So to answer your question, I'd say that no, id() returning the object
address is not, and should not be, a guaranteed aspect of CPython, and
the motivating issue of ctypes is solved within ctypes itself by using