This one is out of the Python Cookbook and credit goes to Alex Martelli if I'm not mistaken. This technique is useful when we would like to record data in some type of "forgiving" data structure.
We know we can accomplish this with a python dictionary, but what about when we want to nest an inconsistent data structure in another inconsistent data structure? This is when the bunch pattern is useful.
Example Program:
class Bunch:
def __init__(self, *args, **kwargs):
self.__dict__.update(kwargs)
struct = Bunch(type="flat", size="huge", family="chordata", genus=Bunch(level="medium", intensity="hot"), BOOL=True)
print struct
print struct.type
print struct.size
print struct.genus.level
Output:
<__main__ .bunch=".bunch" 0x1004e1248="0x1004e1248" at="at" instance="instance">
flat
huge
medium
Pretty slick, huh? The beauty of this vignette is that it is highly extensible. The original thread where I stumbled upon this is located here.
Friday, August 10, 2012
Subscribe to:
Post Comments (Atom)



It's awful because it has no meaning for a code-reader. It can be used for EVERYTHING. If it's a class, it should have some meaning.
ReplyDeleteHow about defaultdict(dict) for nesting?
@aartur
ReplyDeleteIf we were using a statically-type language, I would agree 100%. Everything in Python is an object so there is already some level of confusion in context of structured classes anyway.
You are right in that the code-reader must know what is going on, so explicit commenting is vital. Besides a slight increase in speed, I don't see how defaultdict can be advantageous over the bunch pattern since the bunch pattern is basically a wrapper around a dictionary anyway.
It didn't realize there was a name for this pattern...nice to know, thanks. Btw, pysistence.Expando is worth a look. It let's you apply the Bunch pattern to arbitrary existing classes, which can be useful for writing tests.
ReplyDelete