4

In Swift we can write a function with a completion block like this:

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: () -> ()) {
    print("The quick brown fox")
    completion()
}

And then when we call it, we can put something inside of that block to execute once it's finished it's process:

func thisFunctionNeedsToExecuteSecond() {
   print("jumped over the lazy dog")
}

What is the equivalent in Python?

Max Phillips
  • 6,991
  • 9
  • 44
  • 71
  • 2
    Python functions just execute in order. – Eli Sadoff Jul 03 '16 at 16:52
  • All code executes in order. So even if it's an API call, it won't progress to the next line until the previous function has received a response? And what if I want a function to begin executing, but want the program to continue while it works, once that function has finished I want it to execute something else? – Max Phillips Jul 03 '16 at 17:02
  • Unless you use mutlithreading, the functions will execute in order. – Eli Sadoff Jul 03 '16 at 17:04
  • @spacemonkey "And what if I want a function to begin executing, but want the program to continue while it works (...)" *that* would make a great question :) – Philippe Aubertin Jul 03 '16 at 17:06
  • Gotchya. Alright, well in case anyone was wondering how you do it with Swift, that's the code for it above :) – Max Phillips Jul 03 '16 at 19:16

1 Answers1

5

Python considers functions as objects, meaning you can pass them around (like in Swift, although I'm less familiar with the implementation details in Swift). You can't specify a type in the parameter, of course, since you can't do that with anything in Python, but that's okay. The implementation would look like:

def do_first(completion):
    print("The quick brown fox ")
    completion()

def do_second():
    print("jumped over the lazy dog.")

And then to use them:

do_first(do_second)

Unless you use asynchronous code ahead of the completion() call in the first function, the lines will execute sequentially as expected.

Pierce Darragh
  • 2,072
  • 2
  • 16
  • 29