Pass variable by reference

Ned Batchelder ned at nedbatchelder.com
Tue May 6 17:27:18 EDT 2014


On 5/6/14 5:00 PM, Mark H Harris wrote:
> On 5/6/14 3:31 PM, Ned Batchelder wrote:
>> On 5/6/14 12:42 AM, Gary Herron wrote:
>>> This gets confusing, but in fact the most accurate answer is that Python
>>> does not have "variables", so there is no such thing as passing
>>> "variables" by reference or any other method.  Python *does* have names
>>> bound to values, but that's a very different thing. If necessary, you
>>> may consider that the *values* are passed by reference.
>>
>> This meme bugs me so much.  Python has variables.  They work differently
>> than variables in C.  In fact, they work by having names bound to values.
>
> What does the word "variable" mean. Think BASIC variables. You can set
> them, you can reset them, you can delete them, you can change them.  ...
> because they are variable.

>
> Python has names bound to objects... some of which you may not change.
> Once the name is bound to an object you may bind it to another object,
> but you may not change it, nor may you change the object it is bound to
> if the object is immutable.

I quite like the definition I found on Wikipedia: "a symbolic name 
associated with a value and whose associated value may be changed."  The 
word "change" here is ambiguous: it could mean mutating an existing 
value, or rebinding to another value.  While I can't mutate immutable 
values, I can always rebind a Python name to another value.

Python cannot do "pass variable by reference", but not because it lacks 
variables.  What it lacks is the ability to refer to a variable.  Names 
cannot be referred to, so there is no way to refer to a variable.  This 
is definitely different than C.

You are right about the comparison to BASIC: BASIC's variables can 
always be mutated.  Python's variables cannot always be, because some of 
them have immutable values (or happen to at the moment, they can always 
be rebound!)

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list