Raising exception in a generator, handle it elsewhere and vice versa in python -
i'm thinking in direction more advanced difficult find solutions problem. before coming decision, thought of asking expert advice address problem.
the enhanced generators have new methods .send() , .throw() allow caller pass messages or raise exceptions into generator (coroutine).
from python documentation: can handy, .throw() method requests generator handle exceptions raised in caller.
request #1: example code above statement. didn't find code snippets explanation.
however, i'm considering inverse problem well: can generator raise exception, pass caller, let caller "repair" it, , continue generator's own execution? call "reverse throw".
request #2: example code above statement. didn't find code snippets explanation.
simply raising exceptions in generator not ok. tried "raise someexception" in generator, , didn't work, because after "raise" generator can no longer executed --- stops, , further attempts run generator cause stopiteration exception. in other words, "raise" more deadly "yield": 1 can resume after yielding caller "raise" sends dead end.
i wonder if there simple ways "reverse throw" in python? enable write coroutines cooperate throwing exceptions @ each other. why use exceptions? well, dunno... began rough idea.
case study code:
class myexception(exception):pass def handleerror(func): ''' handle error''' errors =[] def wrapper(arg1): result = func(arg1) err in finderror(result): errors.append(err) print errors return result return wrapper def finderror(result): ''' find error if ''' print result k, v in result.iteritems(): error_nr = v % 2 if error_nr ==0: pass elif error_nr > 0: yield myexception @handleerror def numgen(input): ''' function take input , generates 10 random numbers. 10 random numbers saved in result dictionary indices. find error decorator called based on result dictionary''' random import randint result= {} errors = [] in range(9): j = (randint(0,4)) result[i] = input + j return result if __name__ == '__main__': numgen(4) could explain please both ideas based on case study example(raising exception in generator , handle elsewhere vice versa)? expect pro's , con's of both methods.
thanks in advance.
looking answer drawing credible and/or official sources.
request #1 (example .throw())
i have never used this, could use change behaviour in generator after fact. can .send of course, you'll need deal in line yield expressions (which might in several locations in code), rather centralized try-except block.
def getstuff(): i=0 try: while true: yield i+=1 except valueerror: while true: yield i**2 i+=1 generator = getstuff() print("get numbers...") print(next(generator)) print(next(generator)) print(next(generator)) print("oh, actually, want squares!") print(generator.throw(valueerror)) print(next(generator)) print(next(generator))
Comments
Post a Comment