Pseudo-dicts as properties
-
01-10-2019 - |
Question
I have a Python class C
which should have two pseudo-dict
s a
and b
. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed.
In pseudocode this would look like this:
class C:
def a.__getitem__(self, key):
return 'a'
def b.__getitem__(self, key):
return 'b'
>>> c = C()
>>> c.a['foo']
'a'
>>> c.b['bar']
'b'
I could implement a class for a
and b
, but since both have just a few short methods, I wonder whether there is a more elegant and compact way to do this.
Solution
Why not just define your own class?
class PseudoDict(object):
def __init__(self, c):
self.c = c
def __getitem__(self, key):
return self.c.somethingmagical()
class C(object):
def __init__(self):
self.a = PseudoDict(self)
self.b = PseudoDict(self)
c = C()
print c.a['foo']
print c.b['bar']
I'm not sure where the values for these 'pseudo-dicts' are coming from, so you'll have to update the __getitem__
method.
OTHER TIPS
Like this?
from collections import defaultdict
class C:
a = defaultdict(lambda:'a')
b = defaultdict(lambda:'b')
c=C()
print c.a['foo']
print c.b['bar']
Or maybe like this for real calculation functions?
from collections import defaultdict
class C:
def __init__(self):
self.a = defaultdict(self.geta)
self.b = defaultdict(self.getb)
def geta(self):
return 'a'
def getb(self):
return 'b'
c=C()
print c.a['foo']
print c.b['bar']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow