0

Possible Duplicate:
Python: Get object by id

I have a query, that is, in python if we try this

>>>a=5

>>>id(a)
>>>746363

that is we are getting id , it is equivalent to the address , my query is that ,there is any way to get the value or object from the id , just like we are getting the id from the object

just like as follows,

 >>>object(746363)

 >>>5

I wrote The above one to deliver my query clearly

Community
  • 1
  • 1
neotam
  • 2,611
  • 1
  • 31
  • 53
  • Are you really, really sure you need this? What do you actually want to do? – l4mpi Dec 08 '12 at 10:09
  • yes , i need that, in my project . this came out when i am thinking about the sharing of memory – neotam Dec 08 '12 at 10:33
  • 1
    You don't need this, python already has means to work with share memory. Read again docs about multiprocessing. – graywolf Dec 08 '12 at 12:04
  • @usernaveen This is what I meant, you try to solve problems that have already been solved in the multiprocessing module; also your approach could never work in a modern OS: the "memory address" returned by `id` is, of course, an address in the virtual address space of the process, which has nothing to do with the actual physical address in ram (which btw can change due to paging etc. without the process noticing). Even if you had the actual physical address and locked the page in memory so it wouldn't swap, you couldn't access it from userspace code, only the Kernel could. – l4mpi Dec 08 '12 at 12:31
  • yes i know about that built in module, but here i am working with twisted,for non blocking upto my knowledge that built in multiprocessing module is not sufficient , so that i am searching for something . – neotam Dec 08 '12 at 12:49

1 Answers1

1

First of all, id() returning memory address is CPython implementation detail, and Python gives you no guarantees that it will keep working this way. So you should reconsider it and seek more pythonic approach.

Python does not expose any "good" API to do this, but you can access any memory point with ctypes module. Example from this page:

import ctypes

class PyTypeObject(ctypes.Structure):
    _fields_ = ("ob_refcnt", ctypes.c_int), ("ob_type", ctypes.c_void_p), \
               ("ob_size", ctypes.c_int), ("tp_name", ctypes.c_char_p)

class PyObject(ctypes.Structure):
    _fields_ = ("ob_refcnt", ctypes.c_int), ("ob_type", ctypes.POINTER(PyTypeObject))

PyObjectPtr = ctypes.POINTER(PyObject)

print ctypes.cast(id("test"), PyObjectPtr).contents.ob_type.contents.tp_name
Daniel Kluev
  • 11,025
  • 2
  • 36
  • 36