简体   繁体   中英

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 ther

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.

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).

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

import dis

def hello():
    print("hello")

dis.dis(hello)

That 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.

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 )

But most likely yes, it'll be on heap due to "hello" string being a non-C or non-simple data storage. 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 (eg *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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM