Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inverse function of id(...) built-in function

Is there a reverse or inverse of the id built-in function? I was thinking of using it to encode and decode string without taking too much time or having a lot of overhead like the PyCrypto library. The need for me is quite simple so I don't want to use PyCrypto for a simple encode and decode.

Something like:

>>> id("foobar")
4330174256
>>> reverse_id(4330174256) # some function like this to reverse.
"foobar"
like image 651
user1757703 Avatar asked Jul 18 '14 00:07

user1757703


2 Answers

I do not wanna to steal the credits from the man who answered the question

This can be done easily by ctypes:

import ctypes
a = "hello world"
print ctypes.cast(id(a), ctypes.py_object).value
output:

hello world
like image 93
Victor Castillo Torres Avatar answered Oct 23 '22 13:10

Victor Castillo Torres


I think the base64 module would fit your needs here, rather than trying to use id:

>>> import base64
>>> base64.b64encode("foobar")
'Zm9vYmFy'
>>> base64.b64decode('Zm9vYmFy')
'foobar'

The answer to your literal question (can I look up an object by its id?) is answered here. The short answer is no, you can't. Edit: Victor Castillo Torres ponits out that this actually is possible if you're using CPython, via the ctypes module.

like image 33
dano Avatar answered Oct 23 '22 11:10

dano