function parameter scope python 2.5.2

Arnaud Delobelle arnodel at googlemail.com
Fri Nov 21 02:16:19 EST 2008


J Kenneth King <james at agentultra.com> writes:

> I recently encountered some interesting behaviour that looks like a bug
> to me, but I can't find the appropriate reference to any specifications
> to clarify whether it is a bug.
>
> Here's the example code to demonstrate the issue:
>
> class SomeObject(object):
>
>     def __init__(self):
>         self.words = ['one', 'two', 'three', 'four', 'five']
>
>     def main(self):
>         recursive_func(self.words)
>         print self.words
>
> def recursive_func(words):
>     if len(words) > 0:
>         word = words.pop()
>         print "Popped: %s" % word
>         recursive_func(words)
>     else:
>         print "Done"
>
> if __name__ == '__main__':
>     weird_obj = SomeObject()
>     weird_obj.main()
>
>
> The output is:
>
> Popped: five
> Popped: four
> Popped: three
> Popped: two
> Popped: one
> Done
> []
>
> Of course I expected that recursive_func() would receive a copy of
> weird_obj.words but it appears to happily modify the object.
>
> Of course a work around is to explicitly create a copy of the object
> property befor passing it to recursive_func, but if it's used more than
> once inside various parts of the class that could get messy.
>
> Any thoughts? Am I crazy and this is supposed to be the way python works?

That's because Python isn't call-by-value.  Or it is according to some,
it's just that the values it passes are references.  Which, according to
others, is unnecessarily convoluted: it's call-by-object, or shall we
call it call-by-sharing?  At least everybody agrees it's not
call-by-reference or call-by-name.

There.  I hope this helps!

-- 
Arnaud



More information about the Python-list mailing list