Posted By

ntamas on 03/17/09


Tagged

python unique identifier


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

freephys


Unique ID sequence class


 / Published in: Python
 

A dictionary-like class that can be used to assign unique integer IDs to names. This class is part of the igraph library, but I need it occasionally in other projects so I post it here.

  1. class UniqueIdGenerator(object):
  2. """A dictionary-like class that can be used to assign unique integer IDs to
  3. names.
  4.  
  5. Usage:
  6.  
  7. >>> gen = UniqueIdGenerator()
  8. >>> gen["A"]
  9. 0
  10. >>> gen["B"]
  11. 1
  12. >>> gen["C"]
  13. 2
  14. >>> gen["A"] # Retrieving already existing ID
  15. 0
  16. >>> len(gen) # Number of already used IDs
  17. 3
  18. """
  19.  
  20. def __init__(self, id_generator=None):
  21. """Creates a new unique ID generator. `id_generator` specifies how do we
  22. assign new IDs to elements that do not have an ID yet. If it is `None`,
  23. elements will be assigned integer identifiers starting from 0. If it is
  24. an integer, elements will be assigned identifiers starting from the given
  25. integer. If it is an iterator or generator, its `next` method will be
  26. called every time a new ID is needed."""
  27. if id_generator is None: id_generator = 0
  28. if isinstance(id_generator, int):
  29. import itertools
  30. self._generator = itertools.count(id_generator)
  31. else:
  32. self._generator = id_generator
  33. self._ids = {}
  34.  
  35. def __getitem__(self, item):
  36. """Retrieves the ID corresponding to `item`. Generates a new ID for `item`
  37. if it is the first time we request an ID for it."""
  38. try:
  39. return self._ids[item]
  40. except KeyError:
  41. self._ids[item] = self._generator.next()
  42. return self._ids[item]
  43.  
  44. def __len__(self):
  45. """Retrieves the number of added elements in this UniqueIDGenerator"""
  46. return len(self._ids)
  47.  
  48. def reverse_dict(self):
  49. """Returns the reversed mapping, i.e., the one that maps generated IDs to their
  50. corresponding items"""
  51. return dict((v, k) for k, v in self._ids.iteritems())
  52.  
  53. def values(self):
  54. """Returns the list of items added so far. Items are ordered according to
  55. the standard sorting order of their keys, so the values will be exactly
  56. in the same order they were added if the ID generator generates IDs in
  57. ascending order. This hold, for instance, to numeric ID generators that
  58. assign integers starting from a given number."""
  59. return sorted(self._ids.keys(), key = self._ids.__getitem__)

Report this snippet  

You need to login to post a comment.