Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: subscriptable class

My class Item describes certain items, which are naturally known by their numeric ID (0, 1, 2, ...). I have implemented a registry inside the class, which indexes all the objects by their ID. I also have a method that retrieves an object by its ID:

class Item
    _registry = []
    def __init__(self):
        self._registry.append(self)
        # ...
    @classmethod
    def get_item_by_id(cls, k):
        return cls._registry[k]
    # ...

Is this a reasonable design?

Assuming it is, would it be ok to allow subscripts for the Item class itself? I can (I think) define __getitem__ in Item's metaclass, thus allowing the syntax Item[2] instead of Item.get_item_by_id(2).

If it has any problems (e.g., too weird, can cause undesirable side effects, etc), please let me know.

like image 277
max Avatar asked Feb 11 '26 20:02

max


1 Answers

Nope. That's perfectly fine. It's definitely better than the long form. Just make sure you return sensible exceptions (a KeyError with a descriptive message, e.g. Invalid id for element) when someone uses an incorrect index. Also, make sure that you document this behavior, otherwise there'd be no point in making the object subscriptable in the first place.

like image 155
Rafe Kettler Avatar answered Feb 14 '26 22:02

Rafe Kettler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!