ID generator: class variable vs while yield

Viewed 121

I have some class which gives each instance a unique ID on creation. I can do this in one of 2 ways but do not know which is better practice. The first way is to use a class variable and classmethod to set the ID. A user could mess with this by calling something like SomeClass.unique_id = something but this is very unlikely. The second way is to use a staticmethod with a yield and an infinite while loop. I have shown both methods below (note that both methods only have the same name for example purposes).

class SomeClass():
    
    def __init__(self, *args, **kwargs):
        self.id = self.generate_id()

    # Method 1:
    unique_id = 0
    @classmethod
    def generate_id(cls):
        cls.unique_id += 1
        return cls.unique_id

    # Method 2:
    @staticmethod
    def generate_id():
        unique_id = 0
        while True:
            unique_id += 1
            yield unique_id

Which method is better practice to use in my code?

1 Answers

Consider using itertools.count(), which works basically like your generator function:

import itertools 
class SomeClass:
    id_counter = itertools.count()

    def __init__(self):
        self.id = next(self.id_counter)


a, b = SomeClass(), SomeClass()
print(a.id)  # output: 0
print(b.id)  # output: 1

The issue with the user messing your unique id value by writing something like a.id = 'banana' is another issue, and more or less inherent to Python's flexibility, although you can't really stop them from doing so. If I write np.array = list, that's on me.

Related