Python id() function details | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python id() function details

So, there is a built-in function in Python called id(). It returns the address of the object in memory. But this address is related only to virtual address space, where Python script is running. (correct me if I'm wrong) My question: is it possible to access that memory address from the outside (for example, from another python/cpp script)? If so, how? Example: code1.py from time import sleep x = 550 print("The memory address is", id(x)) sleep(1000) >>> The memory address is 7752762753762 code2.py print(memory_function(7752762753762)) >>> 550

11th Jun 2021, 8:26 PM
DooMx
DooMx - avatar
1 Answer
+ 6
You would most likely only be able to access the value by the returned result from id() within the same program. Most operating systems will/should kill a process that is attempting to access an unexpected memory address (such as an address that is being used by another process/program). The value returned from id() is an identity that is made from the CPython memory address of the variable/object and may or may not contain the actual address info (not sure here). You can get the value of the same object within the same program by looping through all the globals() values and/or locals() values and checking each to see if their id() matches the id you have. This of course is a bit more difficult to do with function attributes as they don't directly fall into the globals or locals.
11th Jun 2021, 8:50 PM
ChaoticDawg
ChaoticDawg - avatar