1

In javascript I can do following:

var some = 100;

var param1 = 1;
func1(param1, function(res1) {

    var param2 = res1 + some;
    func2(param2, function(res2) {
        // ...
    });
});

In php same:

$some = 100;

$param1 = 1;
func1($param1, function($res1) use ($some) {

    $param2 = $res1 + $some;
    func2($param2, function($res2) {
        // ...
    });
});

How can I do same thing in python?

................................................

2
  • Use the lambda statement, or pass the function object. Commented Nov 16, 2013 at 5:48
  • Curious, I did not think there was such thing as a "lambda statement" -- I knew about lambda expressions. But sure enough the phrase appears in the official Python docs. Pedantry aside, the "bodies" of lambda expressions are indeed simple expressions. They are not statements that can hold state in the manner the OP wants. There are probably tricks to make them do so, but in general they are best avoided. Commented Nov 16, 2013 at 5:55

4 Answers 4

3

Pass functions as arguments.

some = 100

def callback1(res1):
    param2 = res1 + some
    func2(param2, callback2)
def callback2(res2):
    ...

param1 = 1
func1(param1, callback1)
Sign up to request clarification or add additional context in comments.

Comments

2

I see that you tagged asynchronous as well. Python is NOT asynchronous. But python functions are also first class objects just like javascript and php. So, you can do the same thing in python as well.

def func1(data, nextFunction = None):
    print data
    if nextFunction:
        nextFunction()

def func(data, nextFunction = None):
    print data
    nextFunction(data * 10)

func(1, func1)

Output

1
10

Inline function definitions are restricted in python but it is still possible with lambda functions. For example,

data = ["abcd", "abc", "ab", "a"]
print sorted(data, key = lambda x: len(x)) # Succinctly written as key = len

Output

['a', 'ab', 'abc', 'abcd']

Comments

1

Functions are first class objects in Python, and you can nest them as well.

EG:

#!/usr/local/cpython-3.3/bin/python

some = 100

param1 = 1

def func1(param1, function):
    param2 = res1 + some;
    def func2(param2, function):
        pass
    func2(param2, function)

Comments

1

Decorators are just syntactic wrappers for "thing that can execute arbitrary code before and after another function." That's what you're doing with a callback, and hey: flat is better than nested.

def func1(fn):
    def wrapped(arg):
        return fn(arg+1)
    return wrapped

def func2(fn):
    def wrapped(arg):
        return fn(arg+2)
    return wrapped

@func1
@func2
def func3(x):
    return x + 3

print(func3(1))
#prints 7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.