Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of id() in Python

Tags:

python

Of what use is id() in real-world programming? I have always thought this function is there just for academic purposes. Where would I actually use it in programming? I have been programming applications in Python for some time now, but I have never encountered any "need" for using id(). Could someone throw some light on its real world usage?

like image 351
Neeraj Avatar asked Apr 27 '11 09:04

Neeraj


4 Answers

It can be used for creating a dictionary of metadata about objects:

For example:

someobj = int(1)
somemetadata = "The type is an int"
data = {id(someobj):somemetadata}

Now if I occur this object somewhere else I can find if metadata about this object exists, in O(1) time (instead of looping with is).

like image 165
orlp Avatar answered Nov 03 '22 00:11

orlp


I use id() frequently when writing temporary files to disk. It's a very lightweight way of getting a pseudo-random number.

Let's say that during data processing I come up with some intermediate results that I want to save off for later use. I simply create a file name using the pertinent object's id.

fileName = "temp_results_" + str(id(self)).

Although there are many other ways of creating unique file names, this is my favorite. In CPython, the id is the memory address of the object. Thus, if multiple objects are instantiated, I'm guaranteed to never have a naming collision. That's all for the cost of 1 address lookup. The other methods that I'm aware of for getting a unique string are much more intense.

A concrete example would be a word-processing application where each open document is an object. I could periodically save progress to disk with multiple files open using this naming convention.

like image 33
John Sallay Avatar answered Nov 03 '22 01:11

John Sallay


Anywhere where one might conceivably need id() one can use either is or a weakref instead. So, no need for it in real-world code.

like image 22
Ignacio Vazquez-Abrams Avatar answered Nov 03 '22 02:11

Ignacio Vazquez-Abrams


The only time I've found id() useful outside of debugging or answering questions on comp.lang.python is with a WeakValueDictionary, that is a dictionary which holds a weak reference to the values and drops any key when the last reference to that value disappears.

Sometimes you want to be able to access a group (or all) of the live instances of a class without extending the lifetime of those instances and in that case a weak mapping with id(instance) as key and instance as value can be useful.

However, I don't think I've had to do this very often, and if I had to do it again today then I'd probably just use a WeakSet (but I'm pretty sure that didn't exist last time I wanted this).

like image 20
Duncan Avatar answered Nov 03 '22 00:11

Duncan