Often we want to just collect a bunch of stuff together, naming each item of the bunch; a dictionary's OK for that, but a small do-nothing class is even handier, and prettier to use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Bunch: def __init__(self, **kwds): self.__dict__.update(kwds) # that's it! Now, you can create a Bunch # whenever you want to group a few variables: point = Bunch(datum=y, squared=y*y, coord=x) # and of course you can read/write the named # attributes you just created, add others, del # some of them, etc, etc: if point.squared > threshold: point.isok = 1
Dictionaries are fine for collecting a small bunch of stuff, each item with a name; however, when names are constants and to be used just like variables, the dictionary-access syntax ("if bunch['squared'] > threshold", etc) is not maximally clear; it takes VERY little effort to build a little class, as in the 'Bunch' example above, that will both ease the initialization task _and_ provide elegant attribute-access syntax ("if bunch.squared > threshold", etc).