Jan-27-2018, 04:00 AM
i have a function that has several places where it needs to finish up and return. the finish up and return code is identical in all cases. in C i did this by having the finish up and return code at the bottom, with a goto label, and goto statements to go down to that point. many C programmers accepted that as the one and only valid use of goto. but Python can't even do that. so i've been thinking about ways to do it and came up with 3 possibilities:
1. a big while loop with a break statement at each place to fall out of the loop, finish up, and return. but this has problems if the main code has other loops and any breakouts are needed inside those inner loops, unless there is a direct way to break out of a specified number of loop lays.
2. two functions a and b. a gets called and calls b. b does the grunt work and all those finish up places are returns back to a. then a does the finish up and returns to the real caller. but this has problems if the finish up in a needs access to variables in b, such as open sockets to databases that need more graceful endings, such as to save changes.
3. the main code wrapped in a try/except with a special new dedicated exception. all those end points in the main code just raise that special new dedicated exception where they would otherwise need to do a goto if it were in C. this method seems to have the most promise.
does anyone know of a better way? what is the more Pythonic way to do this? or should this project be done in C?
1. a big while loop with a break statement at each place to fall out of the loop, finish up, and return. but this has problems if the main code has other loops and any breakouts are needed inside those inner loops, unless there is a direct way to break out of a specified number of loop lays.
2. two functions a and b. a gets called and calls b. b does the grunt work and all those finish up places are returns back to a. then a does the finish up and returns to the real caller. but this has problems if the finish up in a needs access to variables in b, such as open sockets to databases that need more graceful endings, such as to save changes.
3. the main code wrapped in a try/except with a special new dedicated exception. all those end points in the main code just raise that special new dedicated exception where they would otherwise need to do a goto if it were in C. this method seems to have the most promise.
does anyone know of a better way? what is the more Pythonic way to do this? or should this project be done in C?