« back to thoughts

A cute autoincrementing ID table in one line of Python

2017-07-28 · view article source

Consider the following definition:

import collections  # this line doesn't count! :-)
ids = collections.defaultdict(lambda: len(ids))

Whenever we access the ID for a key that isn’t already in the table, it’s inserted into the table with value the number of existing keys. This gives us a very concise implementation of an autoincrementing ID table:

assert ids["alice"] == 0
assert ids["bob"] == 1
assert ids["alice"] == 0

There’s nothing revolutionary here, but the self-referential nature of the dictionary makes it a particularly pleasant implementation.

« back to thoughts