Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #70951

Re: Pass variable by reference

References <mailman.9690.1399348396.18130.python-list@python.org> <53689aeb$0$11109$c3e8da3@news.astraweb.com> <87lhufi85o.fsf@elektro.pacujo.net>
Date 2014-05-06 19:53 +1000
Subject Re: Pass variable by reference
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.9694.1399369998.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, May 6, 2014 at 7:11 PM, Marko Rauhamaa <marko@pacujo.net> wrote:
> Steven D'Aprano <steve@pearwood.info>:
>
>> On Mon, 05 May 2014 17:39:44 -0700, Satish Muthali wrote:
>>> I have a burning question on how to pass variable by reference in
>>> Python. I understand that the data type has to be mutable.
>>
>> [...]
>>
>> To get an effect *similar* to pass-by-reference, you can wrap your
>> variable in a list, and then only operate on the list item.
>
> Consider also returning multiple values in a tuple.
>
> In C:
>
>     stats_read(stats, &characters, &words, &lines);
>
> In Python:
>
>     characters, words, lines = stats.read()

That's not really pass-by-reference, though. What you're doing is
output parameters, which are usually implemented in C with pointers,
but in Python with a return tuple. Pass-by-reference allows the callee
to see and modify something in the caller's environment; for instance,
the stats_read() C function might maintain stats in the three
pointed-to integers, eg incrementing them for each char/word/line
processed. The Python equivalent would need to pass them as parameters
AND return them. For that sort of case, you'd probably want to pass an
object with three attributes (or maybe a dict or a list), which would
then be modified; that's a much closer approximation of
pass-by-reference. Hence Steven's statement about wrapping it in a
list.

And, by the way, it's not purely academic. There have been times when
I've done exactly that as a means of passing state around. It's not
common, but it has its place.

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Pass variable by reference Satish Muthali <satish.muthali@gmail.com> - 2014-05-05 17:39 -0700
  Re: Pass variable by reference Rustom Mody <rustompmody@gmail.com> - 2014-05-05 21:32 -0700
  Re: Pass variable by reference Steven D'Aprano <steve@pearwood.info> - 2014-05-06 08:18 +0000
    Re: Pass variable by reference Marko Rauhamaa <marko@pacujo.net> - 2014-05-06 12:11 +0300
      Re: Pass variable by reference Chris Angelico <rosuav@gmail.com> - 2014-05-06 19:53 +1000
        Re: Pass variable by reference Marko Rauhamaa <marko@pacujo.net> - 2014-05-06 13:38 +0300
          Re: Pass variable by reference Chris Angelico <rosuav@gmail.com> - 2014-05-06 20:45 +1000

csiph-web