nowox
nowox

Reputation: 29096

Append value or create and insert if the list doesn't exist?

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

Answers (1)

timgeb
timgeb

Reputation: 78690

You could call setdefault on the instance dict, i.e.

vars(obj).setdefault('key', []).append(value)

Upvotes: 1

Related Questions