Beginner of Python.

I learned the basics of PHP, but have little other language knowledge.

When I learned PHP, I learned that I manage variable names and values ​​withrefcountandis_refinternally, so I deepened my understanding.

I have read Python's primer, but I'm investigating how it is handled inside Python to better understand it.

I'm investigating and I don't understand the relationship between Python object IDs and memory addresses.

id ()can be used to know the "identity" of an object.

I think this identification value is an object ID.

When you look at the Python documentation, it is described as follows.


CPython implementation details: In CPython, id (x) returns the address in memory where x is stored.


3. Data Model&# 8212;Python 3.6.5 Document

I know that CPython is a processor written in C language.

I'm interested in "memory addresses".

In me, the address on memory is recognized as a hexadecimal number like0x7fffc0c5d57c.

, but in Python'sid (), it is displayed as an integer.

This is a self-evident speculation, but I don't think the addresses in memory are expressed in decimal numbers.

Question 1

Is this theid ()function expressed as an integer based on the memory address?
Or is the object ID assigned to each object regardless of the memory address?

Question 2

It is unknown because the object ID is assigned to each object. However, when this object ID (identity?) is represented internally, it was not known where. (Because my understanding of C language is shallow ;;)

The figure below shows the internal structure when examined.

Source: Python source code阅读-Type

Source: python primordial clan-by type-gradual after-flower garden

If an object ID is assigned to each object, where is it located in the internal structure?

It may be difficult to understand the intention of the question, but if you know it, please tell me m (__) m

  • Answer # 1


    Pointer to PyObject


    Cast to unsigned long


    You've created and returned ainteger object that represents that integer(in the Python language).

    Answer: Integer value cast a pointer to C PyObject to unsigned long

  • Answer # 2

    I just don't understand hexadecimal numbers?

    hoge = id ("hoge")
    print ("{} 0x {: x}". format (hoge, hoge))
    # 139772608496448 0x7f1f58adc340

    139772608496448and0x7f1f58adc340are the same value.

  • Answer # 3

    I don't think what the ID represents is implementation-dependent, and I think that this is about the extent that there may be an implementation that points to the memory address. Let's go.

    Question 1
    Maybe it is the index number of the table holding the object. In such a case, the number is completely unrelated to the address.

    Question 2
    Only the implementer knows that. Keep in mind that Python is not always implemented as such in the process diagram