1

I'm designing a tool which recursively identifies upstream pathways in a vector river network. I'd like to be able to truncate the search if the cumulative path cost passes a test which is defined by the user, and I'm not sure whether this is possible. Below is an example of the sort of thing I'd like to do:

def test1(value):
    if value > 1: return True
    else: return False

def test2(value):
    if value % 4: return True
    else: return False

def main(test):
    for i in range(20):
        if SPECIFIEDTEST(i):
            print i
            break

main(test1)

I know exec() can be used for this purpose but I also understand this is frowned upon? Is there another, better method for passing a function to another function?

3
  • Where's the user input coming from? Commented Feb 25, 2014 at 17:44
  • Functions are first-class entities in python: you can simply pass a function to another function, or bind a local variable to the function and call it that way. So I'm confused by what you're confused about, e.g., did you mean you're looking for something like f = {'test1':test1, 'test2':test2}[key]? (after which f(i) calls the desired function) Commented Feb 25, 2014 at 17:44
  • 1
    def test1(value): return value > 1, etc. You rarely need to use the actual literals True and False. Commented Feb 25, 2014 at 18:03

2 Answers 2

4

Building a dictionary for this is unnecessary, as functions can be passed in as parameters to other functions. Simply pass the function into main()

def test1(value):
    if value > 1: return True
    else: return False

def test2(value):
    if value % 4: return True
    else: return False

# using test1 as the default input value...
def main(test = test1):
    for i in range(20):
        if test(i):
            print i
            break

main(test1)
# prints 2

main(test2)
# prints 1
Sign up to request clarification or add additional context in comments.

3 Comments

Given the poster mentions user-definition and asks about exec I'm assuming string input is involved; that's why a dict is needed.
Sorry, this was a really basic question. I simply wasn't sure whether it was possible to pass a function to another function directly. Thanks for the help.
@tzaman You're right, that's a good assumption. In the case of user inputs as strings, a dictionary would be a good fit. Either way, a variable holding a function is still being passed in.
4

You can create a dictionary that maps function names to the actual functions, and use that:

tests = {'test1': test1, 'test2': test2}
if tests[specifiedtest](i):
    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.