An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
September 29, 2021 03:59 am GMT
Original Link: https://dev.to/rajeshj3/solved-non-default-argument-follows-default-argument-400d
[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}"
- default arguments
def greet(name='Rajesh'): return f"Welcome {name}"
So, a combination of both of these looks something like this
def greet(name, place='Home'): return f"Welcome {name}, to {place}"
The above code is 100% correct. It works great.
But
def greet(name='Rajesh', place): return f"Welcome {name}, to {place}"
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}"
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
Thank you
Cheers
Original Link: https://dev.to/rajeshj3/solved-non-default-argument-follows-default-argument-400d
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To