python - Try-clause containing multiple statements -
let's have following function/method, calculates bunch of stuff , sets lot variables/attributes: calc_and_set(obj).
now call function several times different objects, , if 1 or more fails nothing should set @ all.
i thought this:
try: calc_and_set(obj1) calc_and_set(obj2) calc_and_set(obj3) except: pass
but doesn't work. if instance error happens in third call function, first , second call have set variables.
can think of "clean" way of doing want? solutions can think of rather ugly workarounds.
i see few options here.
a. have "reverse function", robust. if
def calc_and_set(obj): obj.a = 'a' def unset(obj): if hasattr(obj, 'a'): del obj.a
and
try: calc_and_set(obj1) calc_and_set(obj2) except: unset(obj1) unset(obj2)
notice, in case, unset
doesn't care if calc_and_set
completed or not.
b. separate calc_and_set try_calc_and_set
, testing if works, , set
, won't throw errors, , called if try_calc_and_set
didn't fail.
try: try_calc_and_set(obj1) try_calc_and_set(obj2) calc_and_set(obj1) calc_and_set(obj2) except: pass
c. (my favorite) - have calc_and_set
return new variable, , not operate in place. if successful, replace original reference new one. done adding copy first statement in calc_and_set
, , returning variable.
try: obj1_t = calc_and_set(obj1) obj2_t = calc_and_set(obj2) obj1 = obj1_t obj2 = obj2_t except: pass
the mirror of 1 of course save objects before:
obj1_c = deepcopy(obj1) obj2_c = deepcopy(obj2) try: calc_and_set(obj1) calc_and_set(obj2) except: obj1 = obj1_c obj2 = obj2_c
and general comment (if sample code, forgive me) - don't have excepts without specifying exception type.
Comments
Post a Comment