I am not the first one who tried to tackle this issue but I feel I need to write one on my own. To clarify what this is about, a simple example:

print o.attr1.key1

Where o is a normal object and o.attr1 is a dict. You should see you cannot access dictionary item via attribute without adding code to your own dict class. I believe a better way, without touching other’s code, is to do like:

print ot(o, 'attr1.key1')

The goal is to have a unified syntax to access information deep inside of an object. To be honesty, I don’t think it’s often you will need to have such functionality, but when you sure do, you will want something to use right away.

My code is on Gist.

The output:

123
True
2
(1, 2, 3)
['number', 456, {'foo.bar': 'It is foobar!'}]
It is foobar!
s
r

It might not look pretty or magical but it works. Of course, you can wrapping class or object, make special class for inheriting, but often, you don’t have easy way to change. They could be in library and you may need to do some dirty coding. This simple function can do the job well.

You can supply your own key functions, they will be used in order. The key function returns found object or raise KeyError if it cannot find a match. You can also use number as index for list object and dot . for the key in dictionary, just remember to escape it. Also, you can even get a method and run it.

If dictionary key is not string or number, then my code can not access to them.