You can’t use getattr() to look stuff up in a dictionary.
But the ‘default’ feature of getattr() is so useful.
What’s the dict way to do the same thing?

This is one of those posts that I’m writing because I keep having to look it up.
So if I write it, I’ll remember it. Hopefully.

getattr

I’ve been using the ‘default’ parameter to getattr for some time, and it’s super handy.
This is handy in lots of places, and avoids having to wrap things in try/except blocks.

A simple example:

try:
    foo = settings.FOO
except AttributeError:
    foo = None

Can be replaced with:

foo = getattr(settings, 'FOO', None)

dictionary get()

But getattr doesn’t work as I’d expect for dictionaries.
It does something, just not what I would expect.
Mostly, it DOESN’T look up items.

Use get() instead.
Replace:

try:
    foo = aDictionary['FOO']
except KeyError:
    foo = None

With:

foo = aDictionary.get('FOO', None)