Home > other >  in python when we say print("hello"). Does an object with hello is created and stored on h
in python when we say print("hello"). Does an object with hello is created and stored on h

Time:12-07

I am new to python. In python when we say print("hello"). Does an object with hello is created and stored on heap and then printed? or it just print and no object is created on heap.

CodePudding user response:

You can try to disassemble it and you'll see. Python is an interpreted language with its interpreter being a virtual machine (think assembly compiled to machine instructions, but a bit abstracted from the hardware layer to the software layer).

For disassembling Python provides an easy dis.dis() function.

import dis

def hello():
    print("hello")

dis.dis(hello)

It creates the value (I'd guess while parsing, but don't quote me on that. I'd need to check the CPython's code for that) as a constant and then loads it back in the VM when using the print function's C implementation.

Now where it's created is dependent on the underlying Python language interpreter, in this case CPython (and PyPy is another one). For CPython it'd be this:

Memory management in Python involves a private heap containing all Python objects and data structures. (ref)

Not guaranteed for Python as an independent language, but most likely yes, it'd be on heap due to "hello" string being encapsulated in a non-simple data storage (int, char, etc, the low level types). Or better said a Python object (PyObject), which is in general thrown on heap with Python's malloc or so called PyMalloc or other malloc-like implementation the interpreter chooses to use either by compile-time options or library detection on the runtime.

  4           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

However, as noted in the comments, and as with every modern compiler (so even Python's) the code can be optimized, therefore it can be even thrown into a raw C data storage (e.g. *char[] or similar) and then only referenced via the Python's object.

A bit simpler disassembling with just the code you have. dis.dis() accesses the code block in the hello() function, so the result is the same, just the line on the left isn't 4 but a 1

$ cat main.py;echo "---";python -m dis main.py
print("hello")
---
  1           0 LOAD_NAME                0 (print)
              2 LOAD_CONST               0 ('hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE

Related:

CodePudding user response:

I believe it creates a str object which has the method str(), which print() calls, then it gets garbage collected afterwards, but I may be wrong

  • Related