XuMuK
XuMuK

Reputation: 604

Python function which will be applied to another variable

For example:

def some_function(a):
     if a == 1:
          return x ** 2
     else:
          return x - 1000

some_function(a)(b)

And as result when we have a==1, obtain b**2 and in all other cases b-1000.

Is it even possible in python, to get as return some unknown variable, which will be replaced by another?

The question is exactly about not touching b, it will be unreachable for function directly.

And the code which should work is some_function(a)(b).

Upvotes: 1

Views: 160

Answers (4)

nedla2004
nedla2004

Reputation: 1145

The other answers will work, but you may be looking for this.

def first_function(a):
    return a ** 2

def second_function(a):
    return a - 1000

def some_funtion(a):
    if a == 1:
        return first_function
    else:
        return second_function

print(some_function(1)(3)) #prints 9
print(some_function(0)(1500)) #prints 500

Upvotes: 1

Adam Van Prooyen
Adam Van Prooyen

Reputation: 901

Although Brian's answer works, it has code repetition and fails to leverage function closures.

Function closures mean that variables in the scope of the function definition are maintained if after the function is created, even if the variables are now out of scope.

def some_function(a):
    def f(x):
        if a == 1:
            return x ** 2
        else:
            return x - 1000
    return f

some_function(a)(b)

>>> some_function(1)(4)
16
>>> some_function(0)(1000)
0

In this instance, the variable a is only defined in the scope of some_function, but since we use it in f(x) it will still be available when we call the returned function later.

Upvotes: 4

Brendan Abel
Brendan Abel

Reputation: 37549

This is generally referred to as currying or partial functions. It would look like this in python

from functools import partial

def some_function(a, x):
    if a == 1:
        return x ** 2
    else:
        return x - 1000

Generally, you store the partial function

a = 1
func = partial(some_function, a)
func(5)

But you could also just use them as one liners.

partial(some_function, 1)(5)
partial(some_function, 0)(1500)

Alternatively, you could have some_function return a function

def some_function(a):
    if a == 1:
        return lambda b: b **2
    else:
        return lambda b: b - 1000

Using partial is generally the more flexible approach though.

Upvotes: 6

brianpck
brianpck

Reputation: 8254

The other answer is correct in this case, but may not be suitable for what you are trying to do.

What you are trying to do is return a function, which Python makes extremely easy:

def some_function(a):
    if a == 1:
        def f(x):
            return x ** 2
    else:
        def f(x):
            return x - 1000
    return f

>>> some_function(1)(5)
25
>>> some_function(0)(1500)
500

Upvotes: 4

Related Questions