List and Dicts as default args
Fredrik Lundh
effbot at telia.com
Mon Apr 3 05:51:23 EDT 2000
Stefan Migowsky <smigowsky at dspace.de> wrote:
> I was just wondering how to handle lists and dictionaries in
> a simple way as default arguments to functions. Since following
> strange behaviour occured :
when exposed to "strange" behaviour, please check the FAQ
http://www.python.org/doc/FAQ.html#6.25
or the fine manual
http://www.python.org/doc/current/ref/function.html
before posting.
> >>> def f(Index,List = [], Dict = {}):
> ... List.append(1)
> ... List.append(2)
> ... print List
> ... Dict[Index] = Index
> ... print Dict
> >>> f(1)
> [1, 2]
> {1: 1}
> >>> f(2)
> [1, 2, 1, 2]
> {2: 2, 1: 1}
> >>> f(3)
> [1, 2, 1, 2, 1, 2]
> {3: 3, 2: 2, 1: 1}
>
> This behaviour only occurs with dictionaries and list. All other
> types are "well" behaved.
no, they're not. default arguments are created once, when
the function object itself is created. this means that *all*
mutable default values behave the same way -- there is a
single default value, used for all calls. if you modify that in
place, you loose.
(to understand why, you need to dig a little deeper into what
the 'def' statement actually does. see the language reference
for details).
> 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
nice or not, that's the right way to do it.
(note that using Caps for variable names isn't good python
style, but that's another story).
</F>
More information about the Python-list
mailing list