How to do proper refactoring without messing the control flow?

Please consider the following code:

while True:
	foo()
	
	match bar:
		case 0:
			f0()
			if condition:
				continue
			f1()
			
		case 1:
			g0()
			if condition:
				continue
			g1()

	foobar()

I would like to ‘extract’ the code under case 0: into one single function, but I don’t know how, as I can’t continue inside the function.

def f():
	f0()
	continue  # SyntaxError: 'continue' not properly in loop
	f1()

And I don’t like the idea of throwing an exception and catch it in the main loop as it will execute code under the finally block everytime I want to continue. How should I do the refactor properly? I want to do something like this:

while True:
    foo()
    match bar:
        case 0: f()  # Everything inside one single function :)
        case 1: g()
        case 2: h()
        case 3: x()
        case 4: y()
        case 5: z()
        ...  # A LOT of patterns here
    foobar()

Oops, the second code example should be

def f():
	f0()
	if condition:
		continue  # SyntaxError: 'continue' not properly in loop
	f1()

Do your functions inside case-s return something?

If not, then the solution is simple (I think):

def some_f():
     # code, code, code...
     if condition:
         return True
     # the rest of code

#later
while True:
     should_continue = False
     match bar:
         case 1:
              should_continue = some_f()
         #other similar cases...
     if should_continue is True:
         continue
     # code, code, ....
1 Like

Thanks for your answer! How can I not think of that

1 Like