TransWikia.com

Python SyntaxError vs TypeError for repeated keyword arguments

Stack Overflow Asked on December 20, 2021

Python obviously does not allow the same keyword to appear multiple times in function arguments. Here are 2 code samples to show that point:

def foo(a=None, **kwargs):
    pass

Calling this code to produce a SyntaxError:

>>> # Example 1
>>> foo(a=1, a=1)
File "<stdin>", line 1
SyntaxError: keyword argument repeated

Calling this code to produce a TypeError:

>>> # Example 2
>>> foo(1, a=123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'a'

Intuitively, I would expect both examples to raise SyntaxErrors.

Why does the first method produce a SyntaxError while the second method produces a TypeError?

One Answer

From here:

Syntax errors are the most basic type of error. They arise when the Python parser is unable to understand a line of code.

So foo(a=1, a=1) is an invalid python code, while foo(1, a=123) by itself without escope context is a valid python code, thus syntax error is not raised. However, after the code gets parsed, the interpretation of it given the current context fails because the signature of the foo function defined before confuses the interpreter since you have multiple definitions for a.

I can say that it's not a KeyError because you don't have an explicitly dictionary involved. You are passing key words arguments but a dictionary was never created and KeyError is Raised when a mapping (dictionary) key is not found in the set of existing keys. Additionally, from the documentation you linked in the comment, I would say that it's a TypeError because it involves the parsing of the arguments in a function call. But I'm not so sure. Nevertheless, the RuntimeError is a generic exception when no one of the other exceptions fit but the interpreter detected an error.

Answered by Hemerson Tacon on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP