Reputation: 1944
I will have the following code structure in my Python script. But goto is ugly and not allowed to use in Python.
Could some one can suggest a prettier and more pythonic flow design to accomplish this?
PS: I tried to use recursive function call in exception handler, but the program ate plenty of memory after a while.
try:
# label: log_in
login_to_system()
# label: run
while True:
query()
calculate()
update()
# Network exceptions might occur during login and query/update
# Other exceptions might occur during query/calculate/update but do not need to login again.
except SomeNetworkException:
# Need to log in to system again
go to: label log_in
except OtherExceptions:
go to: label run
Updated:
In this case, Network exceptions handler is "shared" by both login and other functions.
Previously, I wrapped login_to_system() function with a try/except block and wrote the same code in login's exception handler, but I felt it was ugly to have the same exception handler code twice in this block.
Upvotes: 0
Views: 3507
Reputation: 215029
I'd rewrite this logic in the following way: move exception handling into the loop and on each iteration check if you need to login:
needs_login = True
while True:
try:
if needs_login:
login_to_system()
needs_login = False
query()
calculate()
update()
except SomeNetworkException:
needs_login = True
except OtherExceptions:
pass
Upvotes: 2