1

I have a function that takes a function as one of its arguments, but depending on the context that function could be one of several (they are all comparator functions for creating rules for the sorted method). Is there any way to check which function was passed into a function? What I'm thinking is some kind of conditional logic like this:

def mainFunction (x, y, helperFunction):
    if helperFunction == compareValues1():
         do stuff
    elif helperFunction == compareValues2():
         do other stuff

etc. Would this work? Would I need to pass in all of the arguments for the function when checking for its existence? is there a better way?

user1427661
  • 11,158
  • 28
  • 90
  • 132

4 Answers4

3

You are on the right track, you just need to remove those parentheses:

def mainFunction (x, y, helperFunction):
    if helperFunction == compareValues1():  <-- this actually CALLS the function!
         do stuff
    elif helperFunction == compareValues2():
         do other stuff

Instead you would want

def mainFunction (x, y, helperFunction):
    if helperFunction is compareValues1:
         do stuff
    elif helperFunction is compareValues2:
         do other stuff
wim
  • 338,267
  • 99
  • 616
  • 750
  • this as opposed to mine verifies that its actually really the function and not just the same name – Joran Beasley Oct 05 '12 at 05:13
  • note: if you are concerned about using the `is` keyword to compare function identity, read Raymond's answer here: http://stackoverflow.com/questions/7942346/how-does-python-compare-functions – wim Oct 05 '12 at 05:46
2
>>> def hello_world():
...    print "hi"
...
>>> def f2(f1):
...    print f1.__name__
...
>>> f2(hello_world)
hello_world

its important to note this only checks the name not the signature..

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1
helperFunction==compareValues1
ninjagecko
  • 88,546
  • 24
  • 137
  • 145
0

Since functions are itself an object in python, So, when you pass a function to your function, a reference is copied to that parameter.. So, you can directly compare them to see if they are equal: -

def to_pass():
    pass

def func(passed_func):
    print passed_func == to_pass   # Prints True
    print passed_func is to_pass   # Prints True

foo = func    # Assign func reference to a different variable foo
bar = func()  # Assigns return value of func() to bar..

foo(to_pass)  # will call func(to_pass)

# So, you can just do: - 

print foo == func   # Prints True

# Or you can simply say: - 
print foo is func   # Prints True

So, when you pass to_pass to the function func(), a reference to to_pass is copied in the argument passed_func

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525