[Tutor] try except block for multiple statements
bob gailer
bgailer at gmail.com
Tue Dec 2 03:31:57 CET 2008
Bryan Fodness wrote:
> I would like to use a try except to see if a value exists. But, when
> I use the following, if a does not exist it exits. I understand why
> this does this, but is there a way to get b,c, and d if a does not
> exist without using a try except for every statement?
>
> try:
> fo.write("a = %s\n" %plan.a)
> fo.write("b = %s\n" %plan.b)
> fo.write("c = %s\n" %plan.c)
> fo.write("d = %s\n" %plan.d)
> except AttributeError:
> pass
>
def foo(obj, attr):
val = getattr(obj, attr, None)
if val is not None:
obj.write("%s = %s\n" % (attr, val))
foo(plan, "a")
foo(plan, "b")
foo(plan, "c")
foo(plan, "d")
> --
> "Any intelligent fool can make things bigger, more complex, and more
> violent. It takes a touch of genius - and a lot of courage - to move
> in the opposite direction. " -Albert Einstein
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list