Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dereference variable id's?

Can you dereference a variable id retrieved from the id function in Python? For example:

dereference(id(a)) == a

I want to know from an academic standpoint; I understand that there are more practical methods.

like image 837
Hophat Abc Avatar asked Feb 21 '13 20:02

Hophat Abc


2 Answers

Here's a utility function based on a (now-deleted) comment made by "Tiran" in a weblog discussion @Hophat Abc references in his own answer that will work in both Python 2 and 3.

Disclaimer: If you read the the linked discussion, you'll find that some folks think this is so unsafe that it should never be used (as likewise mentioned in some of the comments below). I don't agree with that assessment but feel I should at least mention that there's some debate about using it.

import _ctypes

def di(obj_id):
    """ Inverse of id() function. """
    return _ctypes.PyObj_FromPtr(obj_id)

if __name__ == '__main__':
    a = 42
    b = 'answer'
    print(di(id(a)))  # -> 42
    print(di(id(b)))  # -> answer
like image 80
martineau Avatar answered Oct 18 '22 01:10

martineau


Not easily.

You could recurse through the gc.get_objects() list, testing each and every object if it has the same id() but that's not very practical.

The id() function is not intended to be dereferenceable; the fact that it is based on the memory address is a CPython implementation detail, that other Python implementations do not follow.

like image 9
Martijn Pieters Avatar answered Oct 18 '22 02:10

Martijn Pieters