Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the default value of a function input to equal another input in Python

Tags:

Consider the following function, which does not work in Python, but I will use to explain what I need to do.

def exampleFunction(a, b, c = a):     ...function body... 

That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this?

like image 332
Curious2learn Avatar asked Aug 20 '10 19:08

Curious2learn


People also ask

How do you assign a default value to a variable in Python?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

How can default parameter be set in a user defined function in Python?

Introduction to Python default parameters When you define a function, you can specify a default value for each parameter. In this syntax, you specify default values ( value2 , value3 , …) for each parameter using the assignment operator ( =) .

What is default argument in Python?

Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call.

What is the default type of input function in Python?

Python input() Function By default, it returns the user input in form of a string.


2 Answers

def example(a, b, c=None):     if c is None:         c = a     ... 

The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:

def main(argv=None):     if argv is None:         argv = sys.argv 

If None could be a valid value, the solution is to either use *args/**kwargs magic as in carl's answer, or use a sentinel object. Libraries that do this include attrs and Marshmallow, and in my opinion it's much cleaner and likely faster.

missing = object()  def example(a, b, c=missing):     if c is missing:         c = a     ... 

The only way for c is missing to be true is for c to be exactly that dummy object you created there.

like image 86
Nick T Avatar answered Nov 02 '22 11:11

Nick T


This general pattern is probably the best and most readable:

def exampleFunction(a, b, c = None):     if c is None:         c = a     ... 

You have to be careful that None is not a valid state for c.

If you want to support 'None' values, you can do something like this:

def example(a, b, *args, **kwargs):     if 'c' in kwargs:         c = kwargs['c']     elif len(args) > 0:         c = args[0]     else:         c = a 
like image 28
carl Avatar answered Nov 02 '22 10:11

carl