Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic solution for conditional arguments passing

Tags:

python

I have a function with two optional parameters:

def func(a=0, b=10):     return a+b 

Somewhere else in my code I am doing some conditional argument passing like:

if a and b:    return func(a, b) elif a:    return func(a) elif b:    return func(b=b) else:    return func() 

Is there anyway to simplify code in this pattern?

EDIT:

Let's assume that I'm not allowed to implement default parameter logic inside func.

I may have several functions like func: func1, func2 and func3 would all contain the

a = a or 0 b = b or 10 

statements.

But I'm invoking these series of functions to eliminate duplication. (using a decorator)

like image 665
satoru Avatar asked Jun 25 '12 08:06

satoru


People also ask

How do you pass arguments in a Python script?

Many times you need to pass arguments to your Python scripts. Python provides access to these arguments through the sys module. You can directly access the argv functionality and handle the parse of arguments in your own, or you can use some other module as argparse that does that for you.

How do you pass an n number argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

What are the two methods of passing arguments to functions in Python?

By default, arguments may be passed to a Python function either by position or explicitly by keyword.

How can you get the type of arguments passed to a function?

There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.


2 Answers

If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:

>>> def func(a=0,b=10): ...  return a+b ... >>> args = {'a':15,'b':15} >>> func(**args) 30 >>> args={'a':15} >>> func(**args) 25 >>> args={'b':6} >>> func(**args) 6 >>> args = {} >>> func(**args) 10 

or just:

>>>func(**{'a':7}) 17 
like image 173
Vader Avatar answered Oct 11 '22 09:10

Vader


Going by the now-deleted comments to the question that the check is meant to be for the variables being None rather than being falsey, change func so that it handles the arguments being None:

def func(a=None, b=None):    if a is None:       a = 0    if b is None:       b = 10 

And then just call func(a, b) every time.

like image 37
lvc Avatar answered Oct 11 '22 10:10

lvc