'Class with auto-generated unique incremental integer values for attributes (the same as 'enum.auto()' do)

I need Enum-like style for a class to auto-generate vales. I can not use Enum because I need mutability, in other words, I will need to add attributes at runtime.

Pseudo-code:

def auto(attribute_name: str) -> int:
    # Calculate a value for an attribute...
    # E.g. the first attribute will have "1", the second will have "2", etc.
    return value


class Something:
    foo = auto()  # Must be auto-assigned as 1
    bar = auto()  # Must be auto-assigned as 2
    spam = auto()  # Must be auto-assigned as 3
    eggs = auto()  # Must be auto-assigned as 4


assert Something.foo == 1
assert Something.bar == 2
assert Something.spam == 3
assert Something.eggs == 4

Something.add("new_attribute")
assert Something.new_attribute == 5

I want to make sure that I will not reinvent the wheel by writing a lot of custom code. Are the any common ways to solve the issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source