Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
goto problem
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Sounds like you want a context manager.
This is a pretty good introduction: https://jeffknupp.com/blog/2016/03/07/py...-managers/
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  goto jmabrito 34 10,089 Feb-18-2021, 09:55 PM
Last Post: jmabrito
  How to make input goto a different line mxl671 2 2,447 Feb-04-2020, 07:12 PM
Last Post: Marbelous
  Go up script/menu(a goto command) foxtreat 7 8,191 Apr-24-2017, 05:58 PM
Last Post: micseydel
  Is there a goto like there is in BASIC? Luke_Drillbrain 24 14,538 Apr-24-2017, 06:00 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020