Using id () in Python

What is the use of id() in real programming? I always thought that this function exists only for academic purposes. Where will I use it in programming? I have been programming Python applications for some time, but I have never come across any “need” for using id() . Can someone shed light on its actual use in the world?

+7
source share
5 answers

It can be used to create a metadata dictionary about objects:

For example:

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

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

+6
source

Wherever id() may be required, either is or weakref can be used instead. Thus, there is no need for this in real code.

+1
source

The only time I found id() useful outside of debugging or answering questions in comp.lang.python is the WeakValueDictionary, whose dictionary contains a weak reference to the values ​​and discards any key when the last reference to this value disappears.

Sometimes you want to have access to a group (or all) of live instances of a class without increasing the lifetime of these instances, in which case a weak comparison with id(instance) as the key and instance as the value can be useful.

However, I don’t think I had to do this very often, and if I had to do it again today, I would probably just use WeakSet (but I’m sure that didn’t exist the last time I wanted it) .

+1
source

I often use id () when writing temporary files to disk. This is a very easy way to get a pseudo random number.

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

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

Although there are many other ways to create unique file names, this is my favorite. In CPython, an identifier is the memory address of an object. That way, if multiple objects are created, I will never have a name conflict. This is all for 1 search address. Other methods that I know for getting a unique string are much more intense.

A concrete example is a word processing application in which every open document is an object. I could periodically save progress to a disk with several open files using this naming convention.

+1
source

in one program, I used it to calculate the intersection of non-hashables lists, for example:

  def intersection(*lists): id_row_row = {} # id(row):row key_id_row = {} # key:set(id(row)) for key, rows in enumerate(lists): key_id_row[key] = set() for row in rows: id_row_row[id(row)] = row key_id_row[key].add(id(row)) from operator import and_ def intersect(sets): if len(sets) > 0: return reduce(and_, sets) else: return set() seq = [ id_row_row[id_row] for id_row in intersect( key_id_row.values() ) ] return seq 
0
source

All Articles