3

I have this interesting piece of code:

def get_unit_sigmoid_func(alpha: float) -> Callable[[float], float]:
    return lambda x, alpha=alpha: 1. / (1 + (1 / np.where(x == 0, 0.01, x) - 1) ** alpha)

I just don't understand what the point of this is. Why wouldn't they write something like:

def get_unit_sigmoid_func(alpha,x):
    return 1 / (1+(1/np.where(x==0,0.01,x)-1)**alpha)

Is there any advantage to the way it's written in the first way?

martineau
  • 119,623
  • 25
  • 170
  • 301
AI92
  • 387
  • 1
  • 8
  • You can squeeze the number of lines for functions that don't have a lot to do and its a core concept in Functional programming when using functions as arguments of other functions – BoredRyuzaki Mar 03 '21 at 14:29
  • 1
    Does this answer your question? [What is 'Currying'?](https://stackoverflow.com/questions/36314/what-is-currying). Note: Examples on that question are written in JavaScript but please don't dismiss them - the concept applies equally to any language that supports a functional style of programming. – Adam Jenkins Mar 03 '21 at 15:13

1 Answers1

3

The function

def get_unit_sigmoid_func(alpha: float) -> Callable[[float], float]:
    return lambda x, alpha=alpha: 1. / (1 + (1 / np.where(x == 0, 0.01, x) - 1) ** alpha)

returns a function that accepts a float value and an alpha. This function sets a default alpha value, so you don't need to specify it. This is useful when you need a function with a specific signature (e.g., takes one argument), but there are some parameters you want to set first (like alpha).

The function

def get_unit_sigmoid_func(alpha,x):
    return 1 / (1+(1/np.where(x==0,0.01,x)-1)**alpha)

returns the value, but notice that it takes an alpha parameter and a float.

jkr
  • 17,119
  • 2
  • 42
  • 68
  • Ok makes sense. Thank you. Any good resources that further elaborate on these concepts? This is the first time I've seen such detailed type hinting in Python before. – AI92 Mar 03 '21 at 14:34
  • 1
    The first function creates a function that has the __default__ value for `alpha` set, it still allows users to override that. – rdas Mar 03 '21 at 14:34
  • 2
    This is an example of a "partial function application." That search term should help you find lots of resources on the topic. There is support for this here: https://docs.python.org/3/library/functools.html#functools.partial – Metropolis Mar 03 '21 at 14:46