Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call another function and optionally keep default arguments

Tags:

python

I have a function with one optional argument, like this:

def funA(x, a, b=1):
   return a+b*x

I want to write a new function that calls funA and also has an optional argument, but if no argument is passed, I want to keep the default in funA.

I was thinking something like this:

def funB(x, a, b=None):
   if b:
     return funA(x, a, b)
   else:
     return funA(x, a)

Is there a more pythonic way of doing this?

like image 521
itzy Avatar asked Dec 10 '15 15:12

itzy


People also ask

How do you call a function with default value in Python?

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.

Can we overload function with default arguments?

As a guideline, you shouldn't use a default argument as a flag upon which to conditionally execute code. You should instead break the function into two or more overloaded functions if you can.

How do you set optional arguments in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

CAN default arguments be skipped from a function call?

Default arguments can be skipped from function call​.


2 Answers

I would replace if b with if b is not None, so that if you pass b=0 (or any other "falsy" value) as argument to funB it will be passed to funA.

Apart from that it seems pretty pythonic to me: clear and explicit. (albeit maybe a bit useless, depending on what you're trying to do!)

A little more cryptic way that relies on calling funB with the correct keyword arguments (e.g. funB(3, 2, b=4):

def funB(x, a, **kwargs):
    return funA(x, a, **kwargs)
like image 113
LeartS Avatar answered Sep 20 '22 04:09

LeartS


def funA(x, a, b=1):
    return a+b*x

def funB(x, a, b=1):     
   return funA(x, a, b)

Make the default value of b=1 in funB() and then pass it always to funA()

like image 24
k4ppa Avatar answered Sep 19 '22 04:09

k4ppa