On Thu, Mar 24, 2011 at 11:46 AM, Jameson Quinn <jameson.qu...@gmail.com> wrote: >> >> If you need this for **kw arguments maybe you're not using them right; >> why not name your arguments if you're going to reference them by name? > > Good point. >> >> The JSON use case seems to be driven because this is the way >> JavaScript does things -- they don't distinguish between dicts and >> objects. I personally think that's a poor language feature: it blurs a >> line that should be clear, between data (dict keys) and program >> variables (attributes). >> > OK. So if this is a json-only issue, it can be done using a wrapper and > object_hook in the json library. I believe that, since all the magic > functions are pulled from the class, not the instance, you should even be > able to use "if 'a' in wrapped_dict:" and "for a in wrapped_dict:" if your > wrapper class delegates __contains__ and __iter__ to the underlying dict. > Anyway, you can use hasattr for the former. > So my overarching proposal has shrunk to a suggestion that I should go and > make a attrlyjson module which does this by default. I certainly think that > I can get it right, and I know that there are several easy ways to get it > wrong, so it's worth saving people the headache.
You're correct, this is trivial with object_hook. >>> class AttrDict(dict): ... def __getattr__(self, attr): ... try: ... return self[attr] ... except KeyError: ... raise AttributeError(attr) ... >>> import json >>> obj = json.loads('{"foo": {"bar": "baz"}}', object_hook=AttrDict) {u'foo': {u'bar': u'baz'}} >>> obj.foo.bar u'baz' -bob _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com