2

In most languages, including Python, the true value of a variable can be used implicitly in conditions expressions i.e:

    is_selected = True
    If is_selected:
        #do something

Is it possible to create functions that it's arguments behave similarly? For example, if I had a sort function named asort that takes the argument ascending The standard way of calling it would be:

    asort(list, ascending=True)

What I'm envisioning is calling the function like:

    asort(list, ascending)

Edit: The behavior I'm looking for is a little different than default arguments. Maybe sorting is a bad example but let's stay with that, suppose my asort function has a default=False for the ascending argument

def asort(list, ascending=False):
    if ascending: #no need to =True here 
        #sort ascending 
    Else:
        #sort descending

If I want to sort ascending, I must use asort(alist, ascending=True) What I'm wondering is if there is a way to call the non-default ascending asasort(alist, ascending)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

3 Answers3

2

Yes you can define a function with default arguments:

def f(a=True, b=False, c=1):
    print(a,b,c);

f()             # True False 1
f(a=False)      # False False 1
f(a=False, c=2) # False False 2
jspcal
  • 50,847
  • 7
  • 72
  • 76
1

One addition to defaults - don't use it for mutables:

def danger(k=[]):
    k.append(1)
    print(k)

danger()
danger()
danger()
danger()
danger()
danger()

Output:

[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

Fix:

def danger(k=None):
    k = k or []
    k.append(1)
    print(k)

danger()
danger()
danger()
danger()
danger()
danger()

[1]
[1]
[1]
[1]
[1]
[1]

More:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Python has the option of having default arguments in its functions

Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment(=) operator of the form keywordname=value.

So for example

def asort(list, ascending = True):
    *Your function*

will make it so that everytime you call the function asort it will be with ascending set to true to call it you will need to write:

asort(list)

And if you neeed to indicate that ascending is False you need to call it like

asort(list, ascending=False)
Mntfr
  • 483
  • 6
  • 20