Alex Popescu a écrit : > Hi all! > > I am pretty sure this has been asked a couple of times, but I don't seem > to find it on the archives (Google seems to have a couple of problems > lately). > > I am wondering what is the most pythonic way of dealing with missing > keys and default values. > > According to my readings one can take the following approaches: > > 1/ check before (this has a specific name and acronym that I haven't > learnt yet by heart) > > if not my_dict.has_key(key): > my_obj = myobject() > my_dict[key] = my_obj > else: > my_obj = my_dict[key]
if key not in my_dict: my_obj = my_dict[key] = myobject() else: my_obj = my_dict[key] > 2/ try and react on error (this has also a specific name, but...) > > try: > my_obj = my_dict[key] > except AttributeError: > my_obj = myobject() > my_dict[key] = my_obj cf above for a shortcut... > 3/ dict.get usage: > > my_obj = my_dict.get(key, myobject()) Note that this last one won't have the same result, since it won't store my_obj under my_dict[key]. You'd have to use dict.setdefault : my_obj = my_dict.setdefault(key, myobject()) > I am wondering which one is the most recommended way? It depends on the context. wrt/ 1 and 2, use 1 if you expect that most of the time, my_dict[key] will not be set, and 2 if you expect that most of the time, my_dict[key] will be set. > get usage seems > the clearest, but the only problem I see is that I think myobject() is > evaluated at call time, Myobject will be instanciated each time, yes. > and so if the initialization is expensive you > will probably see surprises. No "surprise" here, but it can indeed be suboptimal if instanciating myobject is costly. -- http://mail.python.org/mailman/listinfo/python-list