By value or by reference?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Riccardo Rossi

    By value or by reference?

    Hi all!

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

    Thanks,
    Riccardo Rossi.


  • Roger Irwin

    #2
    Re: By value or by reference?

    Riccardo Rossi wrote:
    [color=blue]
    > Hi all!
    >
    > How does Python pass arguments to a function? By value or by reference?
    >
    > Thanks,
    > Riccardo Rossi.
    >
    >[/color]
    By reference to an object....See the python tutorial.

    Comment

    • Jorge Godoy

      #3
      Re: By value or by reference?

      "Riccardo Rossi" <riccardo.rorss i76@email.it> writes:
      [color=blue]
      > Hi all!
      >
      > How does Python pass arguments to a function? By value or by reference?[/color]

      IIRC, by reference. It uses a copy on write algorithm.

      --
      Godoy. <godoy@ieee.org >

      Comment

      • Jonathan  Ellis

        #4
        Re: By value or by reference?

        Roger Irwin wrote:[color=blue]
        > Riccardo Rossi wrote:
        >[color=green]
        > > Hi all!
        > >
        > > How does Python pass arguments to a function? By value or by[/color][/color]
        reference?[color=blue][color=green]
        > >
        > > Thanks,
        > > Riccardo Rossi.
        > >
        > >[/color]
        > By reference to an object....See the python tutorial.[/color]

        Wrong. Here is the difference between pass by reference and pass by
        value to CS types:
        [color=blue][color=green][color=darkred]
        >>> def foo(a): a = 1[/color][/color][/color]
        ....[color=blue][color=green][color=darkred]
        >>> i = 10
        >>> foo(i)
        >>> print i[/color][/color][/color]

        With pass-by-reference, i would now be 1. However, since python is
        pass-by-value, it remains 10.

        -Jonathan

        Comment

        • Alex Martelli

          #5
          Re: By value or by reference?

          Jonathan Ellis <jbellis@gmail. com> wrote:
          ...[color=blue][color=green]
          > > By reference to an object....See the python tutorial.[/color]
          >
          > Wrong. Here is the difference between pass by reference and pass by
          > value to CS types:
          >[color=green][color=darkred]
          > >>> def foo(a): a = 1[/color][/color]
          > ...[color=green][color=darkred]
          > >>> i = 10
          > >>> foo(i)
          > >>> print i[/color][/color]
          >
          > With pass-by-reference, i would now be 1. However, since python is
          > pass-by-value, it remains 10.[/color]

          ....so you tell "CS types" it's pass-by-value, and they come right back
          with

          def bar(b): b.append(2)

          z = []
          bar(z)
          print z

          With pass-by-value, they'll say, z would still be []. However, since
          what is passed is not just (a copy of) the value, but (a reference to)
          the object itself, z is [2] instead.

          The terminology problem may be due to the fact that, in python, the
          value of a name is a reference to an object. So, you always pass the
          value (no implicity copying), and that value is always a reference.

          I find it simpler to explain as: the semantics of argument passing are
          _exactly_ identical to that of assignment (binding) to a barename; you
          can fruitfully see argument passing as local (bare) names of the called
          function being assigned initial values by the caller (that's exactly
          what happens, in practice). Now if you want to coin a name for that,
          such as "by object reference", "by uncopied value", or whatever, be my
          guest. Trying to reuse terminology that is more generally applied to
          languages where "variables are boxes" to a language where "variables are
          post-it tags" is, IMHO, more likely to confuse than to help.


          Alex

          Comment

          • Oliver Fromme

            #6
            Re: By value or by reference?

            Jonathan Ellis wrote:[color=blue]
            > Roger Irwin wrote:[color=green]
            > > Riccardo Rossi wrote:[color=darkred]
            > > > How does Python pass arguments to a function? By value or by reference?[/color]
            > >
            > > By reference to an object....See the python tutorial.[/color]
            >
            > Wrong. Here is the difference between pass by reference and pass by
            > value to CS types:
            >[color=green][color=darkred]
            > > > > def foo(a): a = 1[/color][/color]
            > ...[color=green][color=darkred]
            > > > > i = 10
            > > > > foo(i)
            > > > > print i[/color][/color]
            >
            > With pass-by-reference, i would now be 1. However, since python is
            > pass-by-value, it remains 10.[/color]

            It remains 10 because integers are immutable, so the function
            code cannot modify the caller's variable anyway. However, if
            you pass a mutable variable, things look a little different:
            [color=blue][color=green][color=darkred]
            >>> def foo(a): a[0] = 1[/color][/color][/color]
            ....[color=blue][color=green][color=darkred]
            >>> i = [10]
            >>> foo(i)
            >>> print i[/color][/color][/color]
            [1]

            Best regards
            Oliver

            --
            Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

            ``All that we see or seem is just a dream within a dream.''
            (E. A. Poe)

            Comment

            • Bruno Desthuilliers

              #7
              Re: By value or by reference?

              Riccardo Rossi wrote:[color=blue]
              > Hi all!
              >
              > How does Python pass arguments to a function? By value or by reference?[/color]

              Both...
              Err, no, none.
              Well...

              *Short answer :*
              args are passed by ref, but bindings are local.

              *Long answer :*
              You first need to understand what 'variables' in Python are. They are in
              fact just a symbol referencing an object. Think of a Python 'variable'
              as an entry in a dict, the name of the variable (the 'symbol') being the
              key and the reference to the object being the value (AFAIK, this is
              exactly what they are).

              You also need to understand the difference between mutable and immutable
              objects. Strings, numerics and tuples are immutables. Which means that
              you can not change them. When doing :
              s = "Hello "
              s += "World"
              .... you are not modifying the string object bound to s, but creating a
              new string object and binding it to s.

              Now for the "By Val/By Ref" stuff... well, try this :

              def my_fun(my_arg):
              print "in my_fun, before rebinding my_arg: my_arg = %s" % my_arg
              my_arg = "42"
              print "in my_fun, after rebinding my_arg: my_arg = %s" % my_arg

              the_arg = "Life, the Universe, and Everything"

              print "before call to my_fun: the_arg = %s" % the_arg
              my_fun(the_arg)
              print "after call to my_fun: the_arg = %s" % the_arg


              You should have somthing like this :

              before call to my_fun: the_arg = Life, the Universe, and Everything
              in my_fun, before rebinding my_arg: my_arg = Life, the Universe, and
              Everything
              in my_fun, after rebinding my_arg: my_arg = 42
              after call to my_fun: the_arg = Life, the Universe, and Everything

              So what ? are we passing args by value ? Well, retry with :

              def my_fun_2(my_arg _2):
              print "in my_fun, before appending to my_arg_2: my_arg_2 = %s" %
              my_arg_2
              my_arg_2.append ("42")
              print "in my_fun, after appending to my_arg_2: my_arg_2 = %s" %
              my_arg_2

              the_arg_2 = ["Life, the Universe, and Everything"]

              print "before call to my_fun_2: the_arg_2 = %s" % the_arg_2
              my_fun_2(the_ar g_2)
              print "after call to my_fun_2: the_arg_2 = %s" % the_arg_2

              and what do we get ?

              before call to my_fun_2: the_arg_2 = ['Life, the Universe, and Everything']
              in my_fun, before appending to my_arg_2: my_arg_2 = ['Life, the
              Universe, and Everything']
              in my_fun, after appending to my_arg_2: my_arg_2 = ['Life, the Universe,
              and Everything', '42']
              after call to my_fun_2: the_arg_2 = ['Life, the Universe, and
              Everything', '42']

              Argh ! So what ? Is it by val or by ref ?
              Ok, let's try a third test :

              def my_fun_3(my_arg _3):
              print "in my_fun, before rebinding my_arg_3: my_arg_3 = %s" % my_arg_3
              my_arg_3 = ["42"]
              print "in my_fun, after rebinding my_arg_3: my_arg_3 = %s" % my_arg_3

              the_arg_3 = ["Life, the Universe, and Everything"]

              print "before call to my_fun_3: the_arg_3 = %s" % the_arg_3
              my_fun_3(the_ar g_3)
              print "after call to my_fun_3: the_arg_3 = %s" % the_arg_3

              An you get :
              before call to my_fun_3: the_arg_3 = ['Life, the Universe, and Everything']
              in my_fun, before rebinding my_arg_3: my_arg_3 = ['Life, the Universe,
              and Everything']
              in my_fun, after rebinding my_arg_3: my_arg_3 = ['42']
              after call to my_fun_3: the_arg_3 = ['Life, the Universe, and Everything']

              err... Time for some explanation ?-)

              When you call a function with an arg, a "local variable" is created,
              which references the object passed as the argument. (well... an entry
              with the formal parameter name as key and a reference to the object
              passed in is created in the 'local' dict).

              So, rebinding this local symbol does not impact the binding in the
              caller's namespace - because the symbol lives in another namespace.

              *But* - and if the object referenced is mutable of course - modifying
              the object in the function... well, just modifies the object, because
              it's the *same* object that is bound to ('referenced by', if you prefer)
              both symbols (the one in the caller's namespace and the one in the
              function's namespace). So yes, the object *is* modified when the
              function returns.

              (Of course, doing anything to an immutable object is just rebinding the
              symbol, so it won't never have any impact outside the function. So don't
              expect to have a function having side-effects on strings, numerics and
              tuples args. The good news being that this is not necessary, since the
              only reason to do so would be to return multiple values, and Python can
              already return multiple values.)


              Does it make sens to you ?-)
              [color=blue]
              > Thanks,
              > Riccardo Rossi.
              >[/color]

              HTH
              Bruno

              (Ho, BTW, please read the fine manual - and this too :
              http://starship.python.net/crew/mwh/...jectthink.html)

              Comment

              • JCM

                #8
                Re: By value or by reference?

                Jorge Godoy <godoy@ieee.org > wrote:[color=blue]
                > "Riccardo Rossi" <riccardo.rorss i76@email.it> writes:[/color]
                [color=blue][color=green]
                >> Hi all!
                >>
                >> How does Python pass arguments to a function? By value or by reference?[/color][/color]
                [color=blue]
                > IIRC, by reference. It uses a copy on write algorithm.[/color]

                Copy-on-write is an optimization. It doesn't affect the semantics of
                the laguage.

                Comment

                • JCM

                  #9
                  Re: By value or by reference?

                  Oliver Fromme <olli@haluter.f romme.com> wrote:
                  ....[color=blue][color=green][color=darkred]
                  > > > > > def foo(a): a = 1[/color]
                  > > ...[color=darkred]
                  > > > > > i = 10
                  > > > > > foo(i)
                  > > > > > print i[/color]
                  > >
                  > > With pass-by-reference, i would now be 1. However, since python is
                  > > pass-by-value, it remains 10.[/color][/color]
                  [color=blue]
                  > It remains 10 because integers are immutable, so the function
                  > code cannot modify the caller's variable anyway. However, if
                  > you pass a mutable variable, things look a little different:[/color]

                  It doesn't matter that integers are immutable. Rebinding formal
                  parameters cannot change variables in the callers scope.
                  [color=blue][color=green][color=darkred]
                  >>>> def foo(a): a[0] = 1[/color][/color]
                  > ...[color=green][color=darkred]
                  >>>> i = [10]
                  >>>> foo(i)
                  >>>> print i[/color][/color]
                  > [1][/color]

                  In this case, you're dereferencing the list (I'm using pointer-
                  terminolgy, but I'm still talking about the behavior of the language,
                  not its implemenation). You're basically modifying the object passed
                  into the function, not rebinding a variable.

                  Comment

                  • Andrew Dalke

                    #10
                    Re: By value or by reference?

                    Jorge Godoy wrote:[color=blue]
                    > IIRC, by reference. It uses a copy on write algorithm.[/color]

                    Really? Where? I've heard theoretical rumblings about
                    that but didn't realized it had been added anywhere.

                    Andrew
                    dalke@dalkescie ntific.com

                    Comment

                    • Michael Hoffman

                      #11
                      Re: By value or by reference?

                      Jonathan Ellis wrote:
                      [color=blue][color=green]
                      >>By reference to an object....See the python tutorial.[/color]
                      >
                      > Wrong. Here is the difference between pass by reference and pass by
                      > value to CS types:[/color]

                      Actually it is a reference to an object being passed.
                      [color=blue][color=green][color=darkred]
                      >>>>def foo(a): a = 1[/color][/color]
                      >
                      > ...
                      >[color=green][color=darkred]
                      >>>>i = 10
                      >>>>foo(i)
                      >>>>print i[/color][/color]
                      >
                      > With pass-by-reference, i would now be 1. However, since python is
                      > pass-by-value, it remains 10.[/color]
                      [color=blue][color=green][color=darkred]
                      >>> def foo(a):[/color][/color][/color]
                      .... print id(a)
                      ....[color=blue][color=green][color=darkred]
                      >>> i = 10
                      >>> id(i)[/color][/color][/color]
                      168377924[color=blue][color=green][color=darkred]
                      >>> foo(i)[/color][/color][/color]
                      168377924

                      With pass-by-value, the memory location of a would be different than the
                      memory location of i. However, since Python is pass-by-reference, it
                      remains the same. <wink>

                      Alex is right that trying to shoehorn Python into a "pass-by-reference"
                      or "pass-by-value" paradigm is misleading and probably not very helpful.
                      In Python every variable assignment (even an assignment of a small
                      integer) is an assignment of a reference. Every function call involves
                      passing the values of those references.
                      --
                      Michael Hoffman

                      Comment

                      • JCM

                        #12
                        Re: By value or by reference?

                        Michael Hoffman <m.h.3.9.1.with out.dots.at.cam .ac.uk@example. com> wrote:
                        ....[color=blue]
                        > With pass-by-value, the memory location of a would be different than the
                        > memory location of i. However, since Python is pass-by-reference, it
                        > remains the same. <wink>[/color]

                        The memory location of the object is the same; the memory location of
                        the reference is different.
                        [color=blue]
                        > Alex is right that trying to shoehorn Python into a "pass-by-reference"
                        > or "pass-by-value" paradigm is misleading and probably not very helpful.
                        > In Python every variable assignment (even an assignment of a small
                        > integer) is an assignment of a reference. Every function call involves
                        > passing the values of those references.[/color]

                        I've given up expressing my opinion on the matter. Everyone here
                        seems to have a different notion of what "pass-by-reference" and
                        "pass-by-value" mean. It's funny--I've never run into trouble with
                        these terms before seeing these discussions on C.L.Py.

                        Comment

                        • Josiah Carlson

                          #13
                          Re: By value or by reference?

                          [color=blue]
                          > I've given up expressing my opinion on the matter. Everyone here
                          > seems to have a different notion of what "pass-by-reference" and
                          > "pass-by-value" mean. It's funny--I've never run into trouble with
                          > these terms before seeing these discussions on C.L.Py.[/color]

                          It is because Python does it differently from most other languages, and
                          it doesn't fit the paradigms of "pass by value" or "pass by reference"
                          as already explained by Alex Martelli.

                          Python does name binding with references. That is, each reference is
                          given a name, but you cannot change data by assigning to a name; you can
                          only change what data that name points to. There are certain operations
                          that can be done with mutable objects and immutable objects, but that is
                          another discussion entirely.


                          There is not so much an argument, but there is a semantic "what the hell
                          is it doing" that is not being communicated properly. I am sure there
                          is a FAQ about this, but I don't have the link handy, and I can't quite
                          find the right incantation for Google.

                          - Josiah

                          Comment

                          • JCM

                            #14
                            Re: By value or by reference?

                            Josiah Carlson <jcarlson@uci.e du> wrote:
                            [color=blue][color=green]
                            >> I've given up expressing my opinion on the matter. Everyone here
                            >> seems to have a different notion of what "pass-by-reference" and
                            >> "pass-by-value" mean. It's funny--I've never run into trouble with
                            >> these terms before seeing these discussions on C.L.Py.[/color][/color]
                            [color=blue]
                            > It is because Python does it differently from most other languages, and
                            > it doesn't fit the paradigms of "pass by value" or "pass by reference"
                            > as already explained by Alex Martelli.[/color]

                            It's really not that different. It's very similar to the way Java
                            handles objects, and how scheme does argument-passing.
                            [color=blue]
                            > Python does name binding with references. That is, each reference is
                            > given a name, but you cannot change data by assigning to a name; you can
                            > only change what data that name points to. There are certain operations
                            > that can be done with mutable objects and immutable objects, but that is
                            > another discussion entirely.[/color]

                            Yes. These two issues often get muddled together in discussions about
                            argument passing. Are you avoiding the term "variable"? Some don't
                            like to use it because they see Python as somehow fundamentally
                            different than other languages. I think the term fits nicely.
                            [color=blue]
                            > There is not so much an argument, but there is a semantic "what the hell
                            > is it doing" that is not being communicated properly. I am sure there
                            > is a FAQ about this, but I don't have the link handy, and I can't quite
                            > find the right incantation for Google.[/color]
                            [color=blue]
                            > - Josiah[/color]

                            Comment

                            • Alex Martelli

                              #15
                              Re: By value or by reference?

                              Josiah Carlson <jcarlson@uci.e du> wrote:
                              [color=blue][color=green]
                              > > I've given up expressing my opinion on the matter. Everyone here
                              > > seems to have a different notion of what "pass-by-reference" and
                              > > "pass-by-value" mean. It's funny--I've never run into trouble with
                              > > these terms before seeing these discussions on C.L.Py.[/color]
                              >
                              > It is because Python does it differently from most other languages, and[/color]

                              Actually, where "real objects" are concerned (there's a slew of
                              exceptions for primitive builtin types such as int) Java has quite
                              similar semantics for both assignment and parameter passing. Python's
                              simpler: no exceptions. C#'s more complicated: besides the types that
                              are built-in exceptions you can also make user-defined types that are
                              also exceptions. But exceptions apart, the 'fundamental' semantics of
                              assignments and assignment passing is similar in all three languages.


                              Alex

                              Comment

                              Working...