[Tutor] Question about large numbers of arguments

Python python at venix.com
Wed Apr 5 14:57:28 CEST 2006


On Wed, 2006-04-05 at 12:34 +0100, Alan Gauld wrote:
> > Suppose you have a situation where you have a large number of command-line
> > options that you will parse with getopt.  You want to keep track of these
> > as you move around in the code and do various things.
> >
> > Is it more Pythonic to:
> >
> > Have the functions take large numbers of parameters.
> >
> > Create an options class to pass the options around.
> 
> Neither, the most Pythonic way IMHO is to use a dictionary and
> possibly combine with Pythons variable arguments syntax as
> described in section 4.7.3/4 of the official tutor.
> 
> > I personally think the latter would look a lot cleaner once the number of
> > options got up to around a half dozen, but I usually see the "large number
> > of parameters" style in other people's code.
> 
> Classes without behaviour are really just glorified dictionaries so
> I prefer to use a dictionary. The **args mechanism provides a
> good way to pass these to functions.

Just to expand on that a little bit, one useful coding trick where you
use only a few of the parameters is to define the function as:

def myfunc(param6, param11, param17, **extra):
	# The parameters you care about are unpacked for you
	# The rest are in extra

# use the ** syntax to pass the dictionary in to your function
myfunc( **param_dict)

Coming up with better names is left as an exercise for the reader.
I mostly use this when dealing with HTML forms with many variables.

> 
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list