Create an incremental ID in a Class in Python

avatar

Borislav Hadzhiev

Last updated: Sep 12, 2022

banner

Photo from Unsplash

Create an incremental ID in a Class in Python #

To create an incremental ID in a class:

  1. Use the itertools.count() method to get an auto-incrementing count object.
  2. Assign the id instance variable to the result of calling next() with the count object.
  3. Each class instance will have a unique id attribute.
main.py
import itertools class Employee(): id_obj = itertools.count() def __init__(self, name, salary): self.id = next(Employee.id_obj) self.name = name self.salary = salary alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 100) carl = Employee('Carl', 100) print(alice.id) # 👉️ 0 print(bob.id) # 👉️ 1 print(carl.id) # 👉️ 2

We used the itertools.count method to make an iterator that returns an auto-incrementing count object.

main.py
import itertools id_obj = itertools.count() print(next(id_obj)) # 👉️ 0 print(next(id_obj)) # 👉️ 1 print(next(id_obj)) # 👉️ 2

Notice that we assign the id attribute of each instance in the __init__() method to the result of calling next() with the count object.

The itertools.count() method takes a start argument that is set to 0 by default.

You can specify a value for the start argument if you need to create an incremental ID that starts at 1 or any other value.

main.py
import itertools class Employee(): # 👇️ start incremental ID at 1 id_obj = itertools.count(1) def __init__(self, name, salary): self.id = next(Employee.id_obj) self.name = name self.salary = salary alice = Employee('Alice', 100) bob = Employee('Bobbyhadz', 100) carl = Employee('Carl', 100) print(alice.id) # 👉️ 1 print(bob.id) # 👉️ 2 print(carl.id) # 👉️ 3

We specified a value of 1 for the start argument, so the auto-incrementing IDs start at 1.

Each time a class instance is created, the __init__() method runs and its id attribute gets set to the result of calling next() with the count object.

An iterator object represents a stream of data. Every time we pass the iterator to the next() function, the next item in the stream is returned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.