Best way to generate a consecutive id in Python

Given a class that has an attribute self.id I need to populate that attribute with a counter starting at 0 and all objects of that class need a unique id during a single run of the program. What is the best/ most pythonic way of doing this? Currently I use

def _get_id():
    id_ = 0
    while True:
       yield id_
       id_ += 1
get_id = _get_id()

which is defined outside the class and

self.id = get_id.next()

in the class' __init__(). Is there a better way to do this? Can the generator be included in the class?

Upvotes: 3

Views: 3347

Answers (3)

Maurici Abad
Maurici Abad

Reputation: 1718

Updated answer for Python 3

Use itertools.count:

from itertools import count

id_counter = count(start=1)
def get_id():
    return next(id_counter)

first_id  = get_id() # --> 1
second_id = get_id() # --> 2

Upvotes: 1

Matt Warren
Matt Warren

Reputation: 696

Why use iterators / generators at all? They do the job, but isn't it overkill? Whats wrong with

class MyClass(object):
  id_ctr = 0
  def __init__(self):
    self.id = MyClass.id_ctr
    MyClass.id_ctr += 1

Upvotes: 4

agf
agf

Reputation: 176910

Use itertools.count:

from itertools import count

class MyClass(object):
    id_counter = count().next
    def __init__(self):
        self.id = self.id_counter()

Upvotes: 6

Related Questions