After some time programming in Javascript I have grown a little fond of the duality there between objects and associative arrays (dictionaries):
//Javascript
var stuff = { a: 17, b: 42 };
stuff.a; //direct access (good sugar for basic use)
stuff['a']; //key based access (good for flexibility and for foreach loops)
In python there are basically two ways to do this kind of thing (as far as I know)
Dictionaries:
stuff = { 'a': 17, 'b':42 };
# no direct access :(
stuff['a'] #key based access
or Objects:
#use a dummy class since instantiating object does not let me set things
class O(object):
pass
stuff = O()
stuff.a = 17
stuff.a = 42
stuff.a #direct access :)
getattr(stuff, 'a') #key based access
edit: Some responses also mention namedtuples as a buitin way to create lighweight classes for immutable objects.
So my questions are:
-
Are there any established best-practices regarding whether I should use dicts or objects for storing simple, method-less key-value pairs?
-
I can imagine there are many ways to create little helper classes to make the object approach less ugly (for example, something that receives a dict on the constructor and then overrides
__getattribute__). Is it a good idea or am I over-thinking it?- If this is a good thing to do, what would be the nicest approach? Also, would there be any good Python projects using said approach that I might take inspiration from?
Not sure about “established best practices”, but what I do is:
**kwargsis a dict, so I’d go with dicts.Or to put it another way, represent instances of data types with objects. Represent ad-hoc or temporary mappings with dicts. Swallow having to use the
['key']syntax – making Python feel like Javascript just feels forced to me.