A question on modification of a list via a function invocation

Steve D'Aprano steve+python at pearwood.info
Mon Sep 4 08:57:06 EDT 2017


On Mon, 4 Sep 2017 06:16 pm, Gregory Ewing wrote:

> Stefan Ram wrote:
>>   JavaScript and Python do not have references as values
> 
> Yes, they do. 

No they don't. Python has ints, floats, strings, lists, tuples, dicts, etc as
values. It has no "reference" type, nor can you define your own. (You can
create a class and call it "reference", but that doesn't make it one.)

You cannot get a reference to either an object, or a name, in Python code. The
value of x here:

x = 1

is the int 1, not a reference to the int 1. Likewise:

y = x

the value of y is the int 1, not a reference to the name x.

Nor does Python have anything like Pascal's "pointer to" operator:

x := ^y;

or the equivalent in C:

x = &y;


nor does Python allow you to write functions with output parameters, like this
C++ code:


void square(int x, int& result) // result is a reference to an int
{
    result = x * x;
}

square(3, y);  // now y has the value 9



Although Python can emulate something close to output parameters by passing a
mutable compound object as the pseudo-output, e.g. by using list slice
assignment:


def square(x, result):
    assert isinstance(result, list)
    result[:] = [x*x]


Nor does Python allow assignment to a function call, as you can do in C++ with
references. Nor can you implement pass-by-reference in Python, as you can do in
C++ with references:

void f_slow(BigObject x) { /* ... */ }  
void f_fast(const BigObject& x) { /* ... */ }


f_slow implements normal pass-by-value semantics, and makes a copy of the
argument passed as x; f_fast implements pass-by-reference semantics, and does
not.


Python has no values which are references. Perhaps you are talking about the
implementation of some Python interpreters, rather than the Python language
itself? If so, you should say so.



> The difference is that they don't have any 
> way of *not* having references as values, 

Of course it does, in the same way it has no way of using unicorns as values.
You can't use what doesn't exist. Since Python does not have references as one
of its first-class values, or as any value at all, you can't use them as
values. All values in Python are objects, not references.



> so there's less 
> need to use the word explicitly in that way -- most of
> the time it's just understood. Nevertheless, terms such
> as "object reference" and "reference to an object" do
> get used in relation to Python when clarity is needed.

Certainly they do. That has nothing to do with the question of whether Python
has references as values.

We use the terms "assignment target", "while loop" and "pass statement" in
Python too, but that doesn't make them values.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list