Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't non-default arguments follow default arguments?

Tags:

python

Why does this piece of code throw a SyntaxError?

>>> def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y
... 
  File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

While the following piece of code runs without visible errors:

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 
like image 758
dotslash Avatar asked Oct 03 '22 11:10

dotslash


People also ask

Can non-default argument follow default argument?

The error “SyntaxError: non-default argument follows default argument” occurs when you specify a default argument before a non-default argument. To solve this error, ensure that you arrange all arguments in your function definition such that the default arguments come after the non-default arguments.

What Cannot be placed by non-default arguments?

7. What we can't place followed by the non-default arguments? Explanation: To avoid the ambiguity in arguments.

Which operator Cannot default arguments?

Overloaded operators cannot have default arguments.

What is default argument give its precedence?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


1 Answers

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

like image 204
Rahul Gautam Avatar answered Oct 21 '22 21:10

Rahul Gautam