Q: List and Dicts as default args
Christian Tismer
tismer at tismer.com
Mon Apr 3 05:43:39 EDT 2000
Stefan Migowsky wrote:
>
> Hi,
>
> I was just wondering how to handle lists and dictionaries in
> a simple way as default arguments to functions. Since following
> strange behaviour occured :
[Stefan, exploring the side effects of mutable default parameters]
> This behaviour only occurs with dictionaries and list. All other
> types are "well" behaved. I could try the following but that
> doesn't look so nice:
>
> def f(Index,List = None, Dict = None):
> if not List: List = []
> List.append(1)
> List.append(2)
> print List
> if not Dict: Dict = {}
> Dict[Index] = Index
> print Dict
The above is correct. When supplying default args, you need
to take care of possible side effects. Lists and dicts are
mutable objects, and the default assignment is done at
compile time.
You can use "real" values as defaults if:
- they are immutable, like ints, strings, tuples
- they are only used for lookup (not changed)
- you *want* to change state permanently
In all other cases, use something like you did above.
ciao - chris
--
Christian Tismer :^) <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH : Have a break! Take a ride on Python's
Kaunstr. 26 : *Starship* http://starship.python.net
14163 Berlin : PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF
we're tired of banana software - shipped green, ripens at home
More information about the Python-list
mailing list