Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of a Swift completion block in Python?

Tags:

python

swift

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?

like image 296
Phil Andrews Avatar asked Oct 18 '25 16:10

Phil Andrews


1 Answers

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.

like image 186
Pierce Darragh Avatar answered Oct 21 '25 05:10

Pierce Darragh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!