0

I'm aware that I cann pass a function name as an argument to another function i.e

def fun_passed(a,b):
    #do something

def main_fun(arg,fun_passed):
    #do something



#call main_fun
first_fun =fun_passed
main_fun(1,first_fun)

Inside main_fun how can I make some checks. For example, Based on the function i passed i want to set a variable

def main_fun(1,fun_passed):
     if fun_passed==first_fun:
             i=1
     else:
             i=10

I can't simply use == because i think that comparison doesn't make sense. Thanks

Marco Fumagalli
  • 2,307
  • 3
  • 23
  • 41
  • 1
    What is the question? You can compare function objects for equality, it will return `True` if both variables refer to the same function. However, it will obviously return `False` if you compare references to two different functions that do exactly the same. – jdehesa Feb 05 '19 at 16:41

3 Answers3

1

You can compare functions for equality, but it's not going to check if the two functions do the exact same thing. Such a check is, in general, undecidable in the technical sense.

Instead, f == g simply returns true if both f and g return to the same underlying object (i.e., it's the same as f is g). This means that something as simple as (lambda x: x) == (lambda x: x) evaluates as False.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

You should use the is keyword:

def fct_a(a,b):
    #do something
    pass

def fct_b(a,b):
    #do something
    pass

def main_fun(fct):
    if fct is fct_a:
        print("fct is 'fct_a'")
    else:
        print("fct is not 'fct_a'")

main_fun(fct_a) # >> fct is 'fun_passed'
main_fun(fct_b) # >> fct is not 'fun_passed'

For more about the differences between is and ==, see there

olinox14
  • 6,177
  • 2
  • 22
  • 39
0

If you are dealing with functions, not a lambda, the function object has a variable __name__ which shows the exact name of the original function. Here a simple example:

>>> def x():
...  return 0;
... 
>>> type(x)
<type 'function'>
>>> x.__name__
'x'
>>> y=x
>>> y.__name__
'x'

So in your case, it will be something like this

if fun_passed.__name__=="first_fun":
rth
  • 2,946
  • 1
  • 22
  • 27