Cool object trick

Fredrik Lundh fredrik at pythonware.com
Sat Dec 18 02:39:47 EST 2004


Carl Banks wrote:

> 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).

this is how your example looks in Python:

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

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

(if you fix the bug in your example, and count the characters, you'll find
that my example is a bit shorter)

with enough keys, you can also save typing by using dummy object instead
of a dictionary, and getting rid of the locals in lookup_reference:

    def lookup_reference(key):
        m = object()
        m.title = ... assign directly to return struct members ...
        m.author = ...
        return m

    m = lookup_reference(...)
    print "%(title)s was written by %(author)s" % vars(m)

</F> 






More information about the Python-list mailing list