DEV Community

Rajesh Joshi
Rajesh Joshi

Posted on

6 3

[Solved]: non-default argument follows default argument

Once in your life, you must have faced this error in Python

non-default argument follows default argument

Why?

In Python, normally you can't define non-default arguments after default arguments in a function, method or class.

  • non-default arguments
def greet(name):
    return f"Welcome {name}"
Enter fullscreen mode Exit fullscreen mode
  • default arguments
def greet(name='Rajesh'):
    return f"Welcome {name}"
Enter fullscreen mode Exit fullscreen mode

So, a combination of both of these looks something like this

def greet(name, place='Home'):
    return f"Welcome {name}, to {place}"
Enter fullscreen mode Exit fullscreen mode

The above code is 100% correct. It works great.

But

def greet(name='Rajesh', place):
    return f"Welcome {name}, to {place}"
Enter fullscreen mode Exit fullscreen mode

Executing this code will log, non-default argument follows default argument.

Solution?

The solution is very simple, just use * at 0th index in the definition.

Example

def greet(*, name='Rajesh', place):
    return f"Welcome {name}, to {place}"
Enter fullscreen mode Exit fullscreen mode

This was introduced in Python 3.4

Don;t forget to pass required keyword arguments while calling the function, method or class

>>> greet(place='School')
Welcome Rajesh, to School
Enter fullscreen mode Exit fullscreen mode

Thank you
Cheers

Top comments (0)

πŸ‘‹ Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple β€œthank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay