Avoiding referencing (was: Python sequences reference - problem?)
Duncan Booth
duncan at NOSPAMrcp.co.uk
Fri Sep 20 04:50:29 EDT 2002
Thorsten Kampe <thorsten at thorstenkampe.de> wrote in news:amejvb$55qsi$1 at ID-
77524.news.dfncis.de:
> Obviously I did not pass 'foo' "by value" to function 'part' but by
> reference and obviously not only local variable 'seq' was modified in
> the function but "outer" variable 'foo', too.
>
> So how to deal with that?
>
You missed out option number 4:
Don't write code that modifies its arguments unless you always want the
arguments modified.
In general, if you want to modify an argument, but don't want the change
reflected back to the caller, make a copy of the argument. If you want the
change reflected back to the caller always, then go ahead and modify the
argument, but make it clear from the function name that it does that. If
you want the function to sometimes modify its argument, then write it so
that it never modifies the argument but returns a modified value as a
result. Then the caller can decide whether to use that result or EXPLICITLY
ignore it.
For the specific example you gave, there was no reason to modify the
argument, the code is just as simple without either copying or modifying:
>>> def part(seq, indices):
partition = []
start = 0
for slice in indices:
partition.append(seq[start:slice])
start = slice
partition.append(seq[start:])
return partition
>>> foo = [11, 22, 33, 44, 55, 66, 77]
>>> part(foo, [2, 3])
[[11, 22], [33], [44, 55, 66, 77]]
>>> foo
[11, 22, 33, 44, 55, 66, 77]
>>>
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list