3

I am trying to get my head around this one.

So here is what I want to do: I have three functions. say, foo,bar and foo_bar

def foo_bar(function):
   for i in range(20):
      function # execute function
def foo(someargs):
   print "hello from foo"

def bar(someargs):
   print " hello from bar"

and when i do foo_bar(foo) # how to specify arguments to foo??

I am expecting that I see "hello from foo" 20 times?

But since I am not seeing that.. I clearly dont understand this well enough?

4 Answers 4

5

You're not calling the function. You call a function called function by following the name function with brackets (), and inside those brackets you put any arguments you need:

function(function)

I've passed function as a parameter to itself because your foo and bar take arguments, but do nothing with them.

Sign up to request clarification or add additional context in comments.

Comments

2

This should do basically what you want:

def foo_bar(function):
   for i in range(20):
      function(i) # execute function
def foo(someargs):
   print "hello from foo"

def bar(someargs):
   print " hello from bar"

foo_bar(foo)
foo_bar(bar)

Comments

2

The docs have a section on this here. You most likely want to construct foo_bar as

def foo_bar(function, *func_args):
    for i in range(20):
        function(func_args)

def foo(a):
    print "hello %s"%a

You can then call it as

foo_bar(foo, 'from foo!')

Comments

0

I would make foo_bar return a function that accept the parameters to pass to the internal function:

def foo_bar(fn, n=20):
    def _inner(*args, **kwargs):
        for i in range(n):
            fn(*args, **kwargs)
    return _inner

and call it like:

foo_bar(foo)('some_param')

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.