At the moment, when you call a function, if there is any mismatch between the function parameters and the supplied arguments, TypeError is raised.
For example: # Too few arguments len() # Too many arguments ord('a', 'b') # Invalid keywords min([], func=len) etc. (There are probably others.) This makes it harder to do feature detection in multi-version code than it need do. Here's an example of feature detection that does work: # math.gcd requires exactly two arguments prior to 3.9 # but soon to take arbitrary number of arguments in 3.9 try: gcd() except TypeError: ... But sometimes its not absolutely clear whether the TypeError is because I've passed the wrong number of arguments or the wrong type of argument: try: foobar(spam='a', eggs=0) except TypeError: ... When I read that, I have to check the documentation to see why a TypeError could be generated. Sure, a comment will help, but comments are notoriously untrustworthy: "At Resolver we've found it useful to short-circuit any doubt and just refer to comments in code as 'lies'." --Michael Foord paraphrases Christian Muirhead on python-dev, 2009-03-22 Proposal: add a new exception, ParameterError, for parameter errors. For backwards compatibility it would have to be a subclass of TypeError. Where the interpreter now raises TypeError for invalid parameters, it will switch to ParameterError. SyntaxErrors will remain SyntaxErrors. min(key=func, values) SyntaxError: positional argument follows keyword argument This will allow developers to distinguish genuine type errors (argument is the wrong type) from other calling errors (argument is the correct type, but passed in the wrong way). Should there be a series of separate exceptions for TooFewArguments, TooManyArguments, InvalidKeywordArgument, etc? No, I don't think so. We don't need to bloat the builtins with three (or more) new exceptions if only one will do. Normally it will be enough for the developer to read the error message, which will distinguish between the various kinds of parameter error. Most people won't care about programmatically distinguishing the cases. Reading the message will be enough. But for stability reasons (what if the error messages are localised, or change in the future?), we could give the exception a "reason" attribute, with a documented stable ID, and make that the official way to programmatically distinguish between the different kinds of parameter errors: except ParameterError as err: if err.reason == 1: # too few arguments The signature could be: ParameterError(*args, *, reason) Thoughts? -- Steven _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/MXPCNEAWXWJPOHB3DC3QW3S3ZPOFSM4Q/ Code of Conduct: http://python.org/psf/codeofconduct/