List and Dicts as default args

Bernhard Herzog herzog at online.de
Mon Apr 3 08:57:47 EDT 2000


"Fredrik Lundh" <effbot at telia.com> writes:

> Stefan Migowsky <smigowsky at dspace.de> wrote:
[mutable default parameters]
> > I could try the following but that doesn't look so nice:
> >
> > def f(Index,List = None, Dict = None):
> >     if not List: List = []

It's probably better to test whether List is None:

	if List is None: List = []

Otherwise, if you actually call f with an empty list as the second
parameter, you'll still create a new list object and won't modify the
list that was passed in.

> >     List.append(1)
> >     List.append(2)
> >     print List
> >     if not Dict: Dict = {}

The same applies here.

> >     Dict[Index] = Index
> >     print Dict
> 
> nice or not, that's the right way to do it.


-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list