says
says

Reputation: 119

How to implement and call a function with another function as an optional argument (filter function)

I'm trying to write a function with a function as an optional argument. I want to use the second function as a filter function

def func1(arg1, arg2, func2, arg4=None):
    # do something with args1,2
    # do something with arg4 if called
    # do something with func2 if called

def func2(arg5):
    # do something

func1(41, "hello there")

In the example above I haven't called func2 . I know I could use a decorator i.e.

def func1(arg1, arg2, func2, arg4=None):
    # do something with args1,2
    func2()
    # do something with arg4 if called

def func2(arg5):
    # do something

func1(41, "hello there")

I'm not sure how to implement or call an optional decorator though. I think the best way would be to make the argument to func2 an argument in func1, func1(arg1,arg2,arg5=None,arg4=None) and then in func1 I could have some logic like this:

def func1(arg1, arg2, arg5=None, arg4=None):
    # do something with args1,2
    if arg5 is not None:
        func2(arg5)
    # do something with arg4 if called

def func2(arg5):
    # do something

func1(41, "hello there")

Any suggestions would be much appreciated!

Upvotes: 0

Views: 110

Answers (1)

AirSquid
AirSquid

Reputation: 11938

Some coding errors pointed out above in comments about code structure need to be fixed. Optional arguments are created by providing a default value. Something like this should get you by:

In [1]: def print_result(x, f=None): 
   ...:     if f: 
   ...:         x = f(x) 
   ...:     print("the final answer is: %i" % x) 
   ...:                                                                         

In [2]: def doubler(x): 
   ...:     return x*2 
   ...:                                                                         

In [3]: print_result(5)                                                         
the final answer is: 5

In [4]: print_result(5, doubler)                                                
the final answer is: 10

Upvotes: 1

Related Questions