How can I accept default parameter in function when 'None' or no argument is passed?
Asked Answered
H

6

5

I am writing a new python class with a generic function. At one point I have a requirement as follows

def function(a=1):
    ....
    ....
    print a # here I want a to be 1 if None or nothing is passed

Eg:

  • a(None) should print 1
  • a() should print 1
  • a(2) should print 2

Is there a way to do this?

Hadrian answered 29/4, 2016 at 7:32 Comment(0)
H
4

You can define a function with a default argument, later you can check for the value passed and print it:

def fun(a=1):
    a = 1 if a is None else a
    print(a)
Holster answered 29/4, 2016 at 7:44 Comment(0)
C
3
def function(a=1):
    if a is None:
        a = 1
Contemporary answered 29/4, 2016 at 7:33 Comment(0)
H
1

Should use None as default parameter.

def function(a=None):
    if a == None:
        a = 1
    print a

Otherwise you'll run into problems when calling the function multiple times.

Heald answered 29/4, 2016 at 7:38 Comment(2)
What do you mean by "calling the function multiple times"? What kind of problems?Gilthead
I suppose the problem mostly arises with mutable data types. Here's a link that explains it nicely: linkHeald
A
0
>>> def function(a=1):
...     print(a if a else 1)
... 
>>> function(None)
1
>>> function(2)
2
>>> function(1)
1
>>> function(123)
123
>>> function(0)
1
Anglicism answered 29/4, 2016 at 7:33 Comment(0)
M
0
def function(a=1):
    print(1 if a is None else a)

function()
function(None)
function(2)
function(0)

Output:

1
1
2
0
Marasco answered 29/4, 2016 at 7:38 Comment(0)
G
0

The default value you specify is going to be used only if you do not pass the value when calling the function at all. If you specified it as a=1 then calling it with zero arguments would indeed use 1 as the default value, but calling it with None will just put None to a.

When I want to give the None and "not specified at all" cases the same meaning, I do this:

def function(a=None):
    if a is None:
        a = 1
    ...

This way it will work as you want. Also, compared to the other solutions like

def function(a=1):
    if a is None:
        a = 1
    ...

you specify the "default" value (the 1) only once.

Gwennie answered 29/4, 2016 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.