views:

553

answers:

3

I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form {Keyword:(FunctionName, AmountofArguments)}.

This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.

Thanks for any help.

+9  A: 

inspect.getargspec():

Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

gimel
Thanks I just discovered that very function as you posted that answer. Thats exactly what I need.
tomeedee
Also since I don't have the rep to edit your answer you have typo in your answer it's getargspec() not getargspect()
tomeedee
Should use inspect.getfullargspec(func) (http://docs.python.org/3.1/library/inspect.html#inspect.getfullargspec) for Python 3.x
Casebash
+2  A: 

What you want is in general not possible, because of the use of varargs and kwargs, but inspect.getargspec comes close:

>>> import inspect
>>> def add(a, b=0):
...     return a + b
... 
>>> inspect.getargspec(add)
(['a', 'b'], None, None, (0,))
>>> len(inspect.getargspec(add)[0])
2
Stephan202
A: 

Make each command a class, derived from an abstract base defining the general structure of a command. As much as possible, the definition of command properties should be put into class variables with methods defined in the base class handling that data.

Register each of these subclasses with a factory class. This factory class get the argument list an decides which command to execute by instantiating the appropriate command sub class.

Argument checking is handled by the command sub classes themselves, using properly defined general methods form the command base class.

This way, you never need to repeatedly code the same stuff, and there is really no need to emulate the switch statement. It also makes extending and adding commands very easy, as you can simply add and register a new class. Nothing else to change.

Ber