[Zope] Another Python Script Question

Dylan Reinhardt zope at dylanreinhardt.com
Fri Dec 5 10:38:59 EST 2003


On Fri, 2003-12-05 at 07:27, Paul Winkler wrote:
> On Thu, Dec 04, 2003 at 08:29:20PM -0800, Dylan Reinhardt wrote:
> > 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
> > ----
> 
> Hey now, let's not get the guy started off with bare excepts.
> It's generally better to catch only the exceptions you anticipate.

I'm firmly in the look-before-you-leap camp, so I won't argue that one. 
That said, there are other potential problems besides AttributeError to
worry about.  The name may be present, but you may have the wrong
arguments or arguments of the wrong type, or it may be a non-callable
attribute, etc.  The idiom becomes vastly less useful when you have to
think up four or five different problems to permit and then question
what else might be lurking in those failures.

I only brought it up because it *is* an idiom in Python.  But I did put
the (IMO) better solution first.  :-)

Dylan




More information about the Zope mailing list