Reputation: 29096
I found myself always writing this kind of ugly snippet when I have to insert a value to a non-existing list:
if hasattr(obj, 'key'):
obj.key = []
obj.key.append(value)
Of course, I could use defaultdict(list)
, but in this use-case I cannot do it a priori.
Is there a more pythonic yet simpler way of achieving this?
Upvotes: 1
Views: 83
Reputation: 78690
You could call setdefault
on the instance dict, i.e.
vars(obj).setdefault('key', []).append(value)
Upvotes: 1