Veronica
Veronica

Reputation: 53

Can I set a default value for an arbitrary argument in python?

Can I set a default value for an arbitrary argument in python? If yes, how to do that... I tried:

def printf(age, gender, *fave, name = "veronica"):

    print(name, " ", gender, " ", age, " ")
    print("favefood: ", end = "")
    for i in fave:
        print(i, end = " ")

printf(25, "f", "water", "grass") 

and I got the output as:

veronica   f   25  
favefood: water grass 

now I want to set a default value for *fave, something like

printf(age, gender, *fave = "grass", name = "veronica")

then I received an error message saying "invalid syntax". So I was wondering if I could really do this for an arbitrary argument...

Upvotes: 1

Views: 489

Answers (3)

Sushant Pachipulusu
Sushant Pachipulusu

Reputation: 6123

It's a 'No' and 'Yes' answer. Ideally you are not meant to have defaults for *args. This is because variable arguments are used when you are not sure of how many arguments are passed (could be 0 too, as suggested by Yash's answer).

If you seriously need a workaround you can check for a null value (None in python) and assign a value for that argument/variable using a simple ternary snippet like below

fave = fave if fave else "grass"

I do have couple of suggestions. It is always recommended to have varargs (*args,*kwargs) at the end of your argument list. In your case you are having another argument called 'name' at the end which is not recommended standard. You need to have your arguments something like below:

def my_func(arg1,arg2,arg3,*args,**kwargs)

Else you can have 'name' as a keyword argument instead of a normal argument. So you can have your function signature like either of the below ways:

def printf(age, gender, name = "veronica", *fave)

def printf(age, gender, *fave, **kwargs)

Please read more about python's variable arguments here

Upvotes: 2

Yash
Yash

Reputation: 396

No You Can't

The entire purpose of *args is so that you can send 0 arguments to it without an error:

def f(*args):
    print(args)
    for arg in args:
        print(arg)

f("foo", "bar", "baz")
print("----------------")
f()
print("----------------")
f("Hello", "World")

Output:

('foo', 'bar', 'baz')
foo
bar
baz
----------------
()
----------------
('Hello', 'World')
Hello
World

How ever you can just use an if statement

def f(*args):
    if args == (): args = ("default value")   ## <--- Here
    print(args)
    for arg in args:
        print(arg)

Upvotes: 3

mipadi
mipadi

Reputation: 410552

Not like that, but you can define your function like this:

def printf(age, gender, *fave, name = "veronica"):
    fave = fave or ["grass"]
    print(name, " ", gender, " ", age, " ")
    print("favefood: ", end = "")
    for i in fave:
        print(i, end = " ")

The output would be:

printf(25, "m", name="john")
john   m   25  
favefood: grass

Upvotes: 1

Related Questions