Pointers in Python

Pointers in Python

Variables in C

Let’s say you had the following code that defines the variable x:

This one line of code has several, distinct steps when executed:

Allocate enough memory for an integer

Assign the value 2337 to that memory location

Indicate that x points to that value

Shown in a simplified view of memory, it might look like this:

Here, you can see that the variable x has a fake memory location of 0x7f1 and the value 2337. Let’s take the equivalent code from the above C example and write it in Python:

Much like in C, the above code is broken down into several distinct steps during execution:

Create a PyObject

Set the typecode to integer for the PyObject

Set the value to 2337 for the PyObject

Create a name called x

Point x to the new PyObject

Increase the refcount of the PyObject by 1

Note: The PyObject is not the same as Python’s object. The Python name x doesn’t directly own any memory address in the way the C variable x owned a static slot in memory.

Source: realpython.com