473,386 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Incorrect number of arguments

I'm trying to keep an open mind, but I am perplexed
about something in Python that strikes me as a poor design.

py> def func(a,b):
py> print a,b
py> func(1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: func() takes exactly 2 arguments (1 given)
Why is the exception raised by passing the wrong number
of arguments a TypeError instead of a more specific
exception?

I'm asking because of a practical problem I had. I have
written some test suites for a module, and wanted a
test to ensure that the functions were accepting the
correct number of arguments, eg if the specs say they
take three arguments, that they actually do fail as
advertised if you pass the wrong number of arguments.

That should be simple stuff to do. Except that I have
to distinguish between TypeErrors raised because of
wrong argument counts, and TypeErrors raised inside the
function.

To add an extra layer of complication, the error string
from the TypeError differs according to how many
parameters were expected and how many were supplied, eg:

func() takes exactly 2 arguments (1 given)
func() takes at least 2 arguments (1 given)
func() takes at most 1 argument (2 given)
etc.

I worked around this problem by predicting what error
message to expect given N expected arguments and M
supplied arguments. Yuck: this is a messy, inelegant,
ugly hack :-( Thank goodness that functions are first
class objects that support introspection :-)

So, I'm wondering if there is a good reason why
TypeError is generated instead of (say) ArgumentError,
or if it is just a wart of the language for historical
reasons?
--
Steven.
Jul 19 '05 #1
2 8163
Steven D'Aprano wrote:
I worked around this problem by predicting what error message to expect
given N expected arguments and M supplied arguments. Yuck: this is a
messy, inelegant, ugly hack :-( Thank goodness that functions are first
class objects that support introspection :-)
*eureka moment*

I can use introspection on the function directly to see
how many arguments it accepts, instead of actually
calling the function and trapping the exception.
So, I'm wondering if there is a good reason why TypeError is generated
instead of (say) ArgumentError, or if it is just a wart of the language
for historical reasons?


Still a good question though. Why is it TypeError?

--
Steven.

Jul 19 '05 #2
Steven D'Aprano wrote:
*eureka moment*

I can use introspection on the function directly to see
how many arguments it accepts, instead of actually
calling the function and trapping the exception.
For funsies, the function 'can_call' below takes a function 'f'
and returns a new function 'g'. Calling 'g' with a set of
arguments returns True if 'f' would take the arguments,
otherwise it returns False. See the test case for an
example of use.
import new

def noop():
pass
def can_call(func):
# Make a new function with the same signature

# code(argcount, nlocals, stacksize, flags, codestring, constants, names,
# varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])
code = func.func_code
new_code = new.code(code.co_argcount,
code.co_nlocals,

noop.func_code.co_stacksize,

code.co_flags,

noop.func_code.co_code, # don't do anything

code.co_consts,
code.co_names,
code.co_varnames,
code.co_filename,
"can_call_" + code.co_name,
code.co_firstlineno,

noop.func_code.co_lnotab, # for line number info

code.co_freevars,
# Do I need to set cellvars? Don't think so.
)

# function(code, globals[, name[, argdefs[, closure]]])
new_func = new.function(new_code, func.func_globals,
"can_call_" + func.func_name,
func.func_defaults)

# Uses a static scope
def can_call_func(*args, **kwargs):
try:
new_func(*args, **kwargs)
except TypeError, err:
return False
return True
try:
can_call_func.__name__ = "can_call_" + func.__name__
except TypeError:
# Can't change the name in Python 2.3 or earlier
pass
return can_call_func
#### test

def spam(x, y, z=4):
raise AssertionError("Don't call me!")
can_spam = can_call(spam)

for (args, kwargs) in (
((1,2), {}),
((1,), {}),
((1,), {"x": 2}),
((), {"x": 1, "y": 2}),
((), {"x": 1, "z": 2}),
((1,2,3), {}),
((1,2,3), {"x": 3}),
):
can_spam_result = can_spam(*args, **kwargs)
try:
spam(*args, **kwargs)
except AssertionError:
could_spam = True
except TypeError:
could_spam = False

if can_spam_result == could_spam:
continue

print "Failure:", repr(args), repr(kwargs)
print "Could I call spam()?", could_spam
print "Did I think I could?", can_spam_result
print

print "Done."

Still a good question though. Why is it TypeError?


My guess - in most languages with types, functions are
typed not only on "is callable" but on the parameter
signature. For example, in C
dalke% awk '{printf("%3d %s\n", NR, $0)}' tmp.c
1
2 int f(int x, int y) {
3 }
4
5 int g(int x) {
6 }
7
8 main() {
9 int (*func_ptr)(int, int);
10 func_ptr = f;
11 func_ptr = g;
12 }
% cc tmp.c
tmp.c: In function `main':
tmp.c:11: warning: assignment from incompatible pointer type
%

'Course the next question might be "then how about an
ArgumentError which is a subclasss of TypeError?"

Andrew
da***@dalkescientific.com

Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Michelle Hillard | last post by:
Hi guys, would appreciate if you can shed some light on this. Sorry to be a pain, can you tell me what is wrong with the following: for /F %%i in ('dir /b /on c:\bcp\pc*.txt') do bcp...
0
by: - | last post by:
i am using the development release of mysql and have a PROCEDURE that executes a prepared statement. it works fine when i call the procedure but repeating it multiple times produces an "incorrect...
3
by: PengYu.UT | last post by:
I quickly searched the group. Like the post said, it is not possible to specify indefinite number of arguments. ...
18
by: John Friedland | last post by:
My problem: I need to call (from C code) an arbitrary C library function, but I don't know until runtime what the function name is, how many parameters are required, and what the parameters are. I...
2
by: gilllyo | last post by:
I'm trying to run a program and pass it arguments. I know that the arguments provided are correct but I get a "The Parameter is incorrect" error. I has used the exact same arguments as provided in...
1
by: ndawg123 | last post by:
Hey guys what im trying to do is write a yatzee game with C. And im stuck already and its the start?!?! I want the user to type there 5 numbers. i.e My program so far does this Please...
2
by: Alan | last post by:
I have a couple of questions about using a variable number of arguments in a function call (...). The context is that I have some mathematical functions I created. I currently pass them a pair of...
20
by: Casey | last post by:
Is there an easy way to use getopt and still allow negative numbers as args? I can easily write a workaround (pre-process the tail end of the arguments, stripping off any non-options including...
16
by: Peng Yu | last post by:
Hi, I'm wondering if there is a min function (in boost, maybe?) that accepts any number of arguments? std::min only accepts two arguments. If I want to get the minimum number out of many, I have...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.