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?

1
  • 3
    What if the user creates their own function? Commented Oct 5, 2012 at 5:03

4 Answers 4

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 
Sign up to request clarification or add additional context in comments.

2 Comments

this as opposed to mine verifies that its actually really the function and not just the same name
note: if you are concerned about using the is keyword to compare function identity, read Raymond's answer here: stackoverflow.com/questions/7942346/…
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..

Comments

1
helperFunction==compareValues1 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.