Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make custom data class subscriptable?

Consider this data class derived from the pydantic package:

from typing import List
from pydantic import BaseModel 


class Bucket(BaseModel):
    setting: List[str]
    fight_1: List[int]
    cause_1: List[str]

let my_bucket be an instance of Bucket:

my_bucket = Bucket(setting=['some_value'], fight_1=[0], cause_1=['other_value'])

basically I would like to be able to do

my_bucket['setting']                                                                                                         

and get back ['some_value'], but instead I get:

---------------------------------------------------------------------------
TypeError                                 
Traceback (most recent call last)
<ipython-input-18-cacbdc1698e9> in <module>
----> 1 my_bucket['setting']

TypeError: 'Bucket' object is not subscriptable
like image 467
user189035 Avatar asked Dec 02 '25 09:12

user189035


2 Answers

With pydantic

You can access your property as an attribute in pydantic.

my_bucket = Bucket(setting=['some_value'], fight_1=[0], cause_1=['other_value'])
print(my_bucket.setting)  # ['some_value']

If you want to use [] to access it, you need to define __getitem__:

from typing import List
from pydantic import BaseModel


class Bucket(BaseModel):
    setting: List[str]
    fight_1: List[int]
    cause_1: List[str]

    def __getitem__(self, item):
        return getattr(self, item)


my_bucket = Bucket(setting=['some_value'], fight_1=[0], cause_1=['other_value'])
print(my_bucket['setting'])  # ['some_value']

Without pydantic

If you don't want to use pydantic and create your custom dataclass you can do this:

from dataclasses import dataclass


@dataclass
class CustomDataClass:
    data: int

    def __getitem__(self, item):
        return getattr(self, item)


obj = CustomDataClass(42)
print(obj.data)  # 42
print(obj["data"])  # 42, needs __getitem__ to be implemented
like image 121
Asocia Avatar answered Dec 05 '25 00:12

Asocia


For a python dataclass this works for me:

from dataclasses import dataclass

@dataclass
class MyCustomRequest:
    request: Dict
        
    def __getitem__(self, key):
        return super().__getattribute__(key)
>>> a = MyCustomRequest({"a":10})
>>> a["request"]
{"a":10}
>>> a.request
{"a": 10}
like image 42
e.arbitrio Avatar answered Dec 05 '25 02:12

e.arbitrio



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!