This post gives a class Dotable
to make nested python dictionaries (json-like objects) accessable using dot notation. I then use this to fill in strings which use ruby’s #{}
format.
Why it’s not there by default
I could’t find a PEP for this, but it’s easy to see the logic to it, for example consider the unruly behaviour of
Anyway, practicality beats purity, so here’s my solution:
-
__getattr__
is the important part which means we can use to dot notation 1. -
The
parse
method is quite general, it takes any json-like object and returns an object whose dictionary part can be accessed with dot notation. I thought this was quite a neat solution (not just because it’s recursive).
Note: Some people on StackOverflow have posted about using dot notation before (2,3,4), but I wasn’t happy with these implementations (to be honest I didn’t look too deeply, and think this is a simpler solution). If you have a nicer way, please leave a comment and let me know!
Example use:
Why I wanted it:
I wanted to populate strings which contained strings with ruby syntax #{blah.foo}
from text files, where blah
a json-like object.
Before you start writing something with evil eval
and regular expression (*then you’ll have two problems!*) to fill in #{blah.foo}
…
You can use format
:
I lied about not using regular expressions, you need a little one to remove the #
s:
Hope this helps.
-
http://stackoverflow.com/questions/224026/javascript-style-dot-notation-for-dictionary-keys-unpythonic/224876#224876 ↩
-
http://stackoverflow.com/questions/224026/javascript-style-dot-notation-for-dictionary-keys-unpythonic ↩
-
http://stackoverflow.com/questions/3031219/python-recursively-access-dict-via-attributes-as-well-as-index-access ↩
-
http://stackoverflow.com/questions/3797957/python-easily-access-deeply-nested-dict-get-and-set ↩