WoJ WoJ - 19 days ago 9
Python Question

Is it pythonic to reuse a feature of a dict, but not for dict-like features?

I would like to use the bracket expression used to access a value in a

dict
, but without any other
dict
features.

In the example below, I use the expression
variable[something]
to query
variable
in the same way as a
dict
. There are no other functionalities of a
dict
behind, what is returned is computed (it is either a color when
something
is
'color'
, or
"hello"
for anything else).

import random

class ColDict(dict):
def __init__(self, *args):
dict.__init__(self, args)
self.colors = ['blue', 'white', 'red']
def __getitem__(self, item):
if item == 'color':
random.shuffle(self.colors)
return(self.colors[0])
else:
return("hello")

if __name__ == "__main__":
col = ColDict()
print(col['color'], col['color'], col['something']) # red white hello (changes on each call)


This code works as expected.

What I would like to understand is whether the reuse of a dict functionality (the bracket call) is pythonic, or at last acceptable.

Note: I understand that this could be accomplished though other means (liek a function) but I am specifically instersted in reusing the brackets call. Reusing, not misusing (which is the core of my question)

Answer

If you don't need any functionality from dict, just provide __getitem__()

import random

class ColDict:
    def __init__(self, *args):
        self.colors = ['blue', 'white', 'red']
    def __getitem__(self, item):
        if item == 'color':
            return random.choice(self.colors)
        else:
            return("hello")

if __name__ == "__main__":
    col = ColDict()
    print(col['color'], col['color'], col['something']) # red white hello (changes on each call)

read more about it