[Zope] Another Python Script Question

Dylan Reinhardt zope at dylanreinhardt.com
Thu Dec 4 23:29:20 EST 2003


On Thu, 2003-12-04 at 18:44, Tim Zegir wrote:
[much snipping]

> Thank you all for your help so far.

I'm going to go ahead and do the classic usenet thing here and not
answer your question.  Your basic problem is, your question is wrong. 
Proper error handling is the least of your concerns at this point.

Since you're just getting started in Python, don't worry about how to
handle errors within error handlers.  That is not important.  What *is*
important is understanding why your code isn't correct and learning how
to fix those problems.

Python uses some well-worn idioms for this kind of stuff that are worth
knowing about.  The more you use them, the better you'll program.

First off, there is almost never any good reason to call something and
handle the case that it's not there.  The more Pythonic way is to
iterate over a collection of things that *are* there.  Ex:

----
for obj in context.objectValues('Folder'):
    print obj.getId()
return printed
----

There is no need to figure out what you do about unresolved names
because you start with the set of names you want to work with.  If no
objects match your criteria, you'll do zero iterations.  This idiom has
almost no special cases... for the most part, it just works.

Or let's say some group of objects have an attribute called foo and some
don't.  Rather than handle failure cases, you can avoid them completely:

----
for obj in context.objectValues():
    if hasattr(obj, 'foo'):
        print obj.foo
return printed
----

There's no need to break flow and go to some error-handling code like
you might do in VB.  If it won't work, don't do it.  Python provides
some very sophisticated tools for examining objects.  Use 'em.

There is also school of thought in Python that "it is easier to ask
forgiveness than permission".  In other words, go ahead and do what
you're going to do, but skip the predictable failure cases.  

This idiom is most often used in the cases where different objects may
support similar interfaces.  Instead of checking object type, you can
just *try* using the interface you expect, ex:

----
for obj in context.objectValues()
    try:
        print obj.foo()
    except: 
        pass
return printed
----

As you get into Python, I'd encourage you to read Alex Martelli's Python
in a Nutshell and the O'Reilly Python Cookbook.  These are indispensable
references to good Python style.

I know that doesn't answer your question, exactly... but hope it helps
anyway.

Dylan




More information about the Zope mailing list