I am having a use case where I want to store a key value pair in dictionary. The problem I'm facing is my key is 'copy'. So after inserting 'copy' key, I'm not able to access it via getattr method, since it always returns the copy method of dict.
I cannot use get method on dict because my code is unaware of the type of object that is being passed. So, I went ahead with using getattr which is generic function to access properties.
I also created a custom class inheriting from dict and wrote getattribute but that blocks access to methods
class DictLike(dict):
def __getattribute__(self, k):
try:
return self[k]
except KeyError:
getattr(super(DictLike, self), k)
def paste(self):
return "Test"
a = DictLike()
a['copy'] = 1;
a['state'] = 'completed'
print(getattr(a, 'copy')) // prints 1
print(a.paste()) // this does not works
b = {'copy': 1}
print(b.get('copy')) \\ 1
getattr(b, 'copy') \\ function
Is there a way I could fix this behavior ?