Collecting a Bunch of Named Items
Credit: Alex Martelli
Problem
You want to collect a bunch of items together, naming each item of the bunch, and you find dictionary syntax a bit heavyweight for the purpose.
Solution
Any (classic) class inherently wraps a dictionary, and we take advantage of this:
class Bunch:
def _ _init_ _(self, **kwds):
self._ _dict_ _.update(kwds)Now, to group a few variables, create a Bunch
instance:
point = Bunch(datum=y, squared=y*y, coord=x)
You can access and rebind the named attributes just created, add others, remove some, and so on. For example:
if point.squared > threshold:
point.isok = 1Discussion
Often, we just want to collect a bunch of stuff together, naming each item of the bunch; a dictionary’s okay for that, but a small do-nothing class is even handier and is prettier to use.
A dictionary is fine for collecting a few items in which each item has a name (the item’s key in the dictionary can be thought of as the item’s name, in this context). However, when all names are identifiers, to be used just like variables, the dictionary-access syntax is not maximally clear:
if point['squared'] > threshold
It takes minimal effort to build a little class, as in this recipe, to ease the initialization task and provide elegant attribute-access syntax:
if bunch.squared > threshold
An equally attractive alternative implementation to the one used in the solution is:
class EvenSimplerBunch:
def _ _init_ _(self, **kwds): self._ _dict_ _ = kwdsThe alternative presented ...