13

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"
2
  • base64 might fit your needs better... Commented Jul 18, 2014 at 0:51
  • 9
    id is not a string encoding function. It returns a unique ID for the passed object, which may change between runs. Commented Jul 18, 2014 at 0:52

2 Answers 2

19

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
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, cool! I guess I didn't scroll far enough down the page. I still think base64 is much more appropriate for what the OP is trying to do here, though.
@dano I think so too but he answered Is there a reverse or inverse of the id built-in function?
Oh, for sure (which is why I upvoted you). But sometimes the OP thinks they needs an answer for one question, when they really need a different answer to a different question.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.