Cool object trick

Carl Banks imbosol at aerojockey.com
Fri Dec 17 21:03:01 EST 2004


Alex Stapleton wrote:
> Hmm true, (i had forgotten about getattr :/) in that case im
indifferent
> to Bunch() not that i really see why it's useful except for making
code
> look a bit nicer occasionaly.

When using Bunch, the idea is not to access the elements indirectly.
If you need to access elements indirectly, you ought to be using a dict
(of course).  But sometimes (perhaps often) it's useful to bundle a
bunch of variables together, to be accessed directly.

Say, for example, you are writing a function that returns a variety of
unrelated information (unrelated in that it doesn't make sense to
perform operations on them).  One thing you could do is return a tuple,
but that could be unwieldy if you have too many items.  Instead, you
could return a Bunch.  For example:

.    def lookup_reference(key):
.        ....
.        return Bunch(title=title,author=author,...)

The code quickly and easily returns a object with the desired keys.
The code that calls this function would access the return values
directly, like this:

.    m = lookupreference()
.    print "%s was written by %s" % (m.title,m.author)

You could still use a dict for this, but a Bunch class neater and more
concise (not to mention less typing).


-- 
CARL BANKS




More information about the Python-list mailing list