Reputation: 107
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:
Is there a way to do this?
Upvotes: 5
Views: 3720
Reputation: 1057
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)
Upvotes: 4
Reputation: 8419
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.
Upvotes: 0
Reputation: 21619
def function(a=1):
print(1 if a is None else a)
function()
function(None)
function(2)
function(0)
Output:
1
1
2
0
Upvotes: 0
Reputation: 6616
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.
Upvotes: 1
Reputation: 8769
>>> 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
Upvotes: 0