Reputation: 13908
I want to pass a function into another function, but use the scope of the second function inside the first. I have a javascript background, so I'm used to doing things like:
function write(str, path) {
// do stuff
}
function doThis(fn) {
fn()
}
function doThisString(str, path) {
doThis(function() {
write(str, path)
});
}
How can i do this in python?
Upvotes: 0
Views: 60
Reputation: 9323
Here is how it would look syntactically in python:
def write(text, path):
// do stuff
def doThis(fn):
fn()
def doThisString(text, path):
doThis(lambda: write(text, path) )
Upvotes: 0
Reputation:
Yes, Python supports closures. But except for the very limited (only a single expression) lambda
form, functions must be defined in a separate statement before being used - they can't be created in an expression.
If you want to avoid nested function definitions for the sake of avoiding nesting, you can use functools.partial
. Your specific example would be greatly simplified by it anyway:
from functools import partial
def doThisString(str, path):
doThis(partial(write, str, path))
It doesn't always work out that well, so sometimes there are better alternatives.
Upvotes: 2
Reputation: 32429
The python equivalent would be.
def write (mystr, path): pass
def doThis (f): f ()
def doThisString (mystr, path):
doThis (lambda: write (mystr, path) )
Or alternatively:
def doThisString (mystr, path):
def function (): write (mystr, path)
doThis (function)
Upvotes: 2