2

I'm wondering whether python have pointers to operate. Also, I've heard that every variable even like int and strings is an object. Can anyone tell me the low-level implementation of python's variable?

I don't understand why every variable is an object. Then does it have basic, indivisible structure that is not an object?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Dan
  • 29
  • 3
  • It has a module `ctypes` for direct low-level interaction with pointers and compiled machine code functions. Generally, Python has no pointers. A variable holds a reference (usually implemented as pointer) to an object. Everything, including ints and such basic things, is an object. – Michael Butscher Apr 20 '23 at 03:16
  • 2
    Python has two things: names and objects. That's it. Things like `1` and `"abc"` and `[1,2,3]` are objects. Names can be bound to objects. That's really the fundamentals of the "variable" system. It's not necessarily useful to think of "variables". A name is just something that is bound to an object. When you supply a name as a parameter to a function, you are passing the object it is bound to, not the name. – Tim Roberts Apr 20 '23 at 03:17
  • You should also distinguish between the abstract Python language, defined by its standard documents, and a specific implementation like CPython (the most common one). – Michael Butscher Apr 20 '23 at 03:19
  • I have the feeling this is a duplicate, but I could not quickly locate a question which discusses the internal implementation of objects and references. I assume you want a beginner-friendly exposition rather than a review of the actual C code. – tripleee Apr 20 '23 at 04:23

1 Answers1

4

The short answer is "yes."

The reference implementation of Python is CPython which is, as its name suggests, written in C. And yes, everything is an object (even integers and Booleans). In fact, the values True and False are singletons. Integer values are just objects too (the numbers -5 through, IIRC, 255 or so are singletons as well).

All Python objects consist of, at a minimum, a reference count, type metadata, and support for a doubly linked list of all objects on the heap:

struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
};

_PyObject_HEAD_EXTRA is a macro used to support a doubly linked list of all heap objects. ob_refcnt is the reference count. *ob_type is type information.