By value or by reference?

Jacek Generowicz jacek.generowicz at cern.ch
Tue Oct 19 04:26:41 EDT 2004


"Riccardo Rossi" <riccardo.rorssi76 at email.it> writes:

> How does Python pass arguments to a function? By value or by reference?

[Or maybe "by name", or even "by need" ?]

Don't take anyone's word for it. Check for yourself.

Here's a program that tells you the answer. Should be trivially
translatable to many other languages.

========================================================================
def passCheck(b):
    b = 'new'

def doesThisLanguageBindByValue(language):
    a = 'original'
    b = a
    b = 'new'
    if a == 'original':
        print "%s assigns by value" % (language)
    else:
        print "%s does not assigns by value" % (language)

    a = 'original'
    passCheck(a)
    if a == 'original':
        print "%s passes by value" % (language)
    else:
        print "%s does not pass by value" % (language)

doesThisLanguageBindByValue('Python')
========================================================================



Caveat: Once you've convinced yourself that the answer is "by value",
do notice that the values are references, so you can give the
impression that you have by-reference semantics, by passing or
assigning a mutable object and mutating it. But the _binding_
mechanism is most certainly "by value".



More information about the Python-list mailing list