self
self

Reputation: 33

how to get an argument from an outer function? python

I would like to create a function with one string argument. This function should return an anonymous function that checks if the function argument is equal to the argument of the external function. But I do not understand how to get the argument of an external function.

def create(arg): 
     outer = 

     return lambda a: outer == arg

firstValue = create("secret")

print(firstValue("secret"))  # >> True

print(firstValue("SECRET"))  # >> False

Upvotes: 0

Views: 401

Answers (1)

moctarjallo
moctarjallo

Reputation: 1615

def create(arg): 
     return lambda a: a == arg # replace outer with a

firstValue = create("secret")

print(firstValue("secret"))  # >> True

print(firstValue("SECRET"))  # >> False

Edit: (for explanation)

The first function, create("secret"), takes as argument arg = "secret". Following the execution of its body, it creates the other lambda function that takes as argument a and compares it to "secret"; that function is returned. Again, remember that the function that is being returned is a function that takes one parameter a and compares it to the value "secret"; it's as if you just did manually this:

def anonymous(a):
   return a == "secret"

That's the function that is returned. Now you are assigning this returned function to the name firstValue; it's as if you are doing this: firstValue = anonymous.

Finally you are just calling THIS function with argument a="secret" or a="SECRET", which obviously returns True in the first case and False in the second.

Upvotes: 1

Related Questions