Easy questions from a python beginner

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 12 06:09:30 EDT 2010


"Alf P. Steinbach /Usenet" <alf.p.steinbach+usenet at gmail.com> wrote:

> * sturlamolden, on 12.07.2010 06:52:
>> On 11 Jul, 21:37, "Alf P. Steinbach /Usenet"<alf.p.steinbach
>> +use... at gmail.com>  wrote:
>>
>>> Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo.
>>> Python works like Java in this respect, that's all; neither Java nor
>>> Python support 'swap'. 
>>
>> x,y = y,x
>>
> 
> We're talking about defining a 'swap' routine that works on variables.
> 
> Since Java/Python doesn't support pass by reference of variables it's
> not possible in these languages, i.e., you missed the point, or made a
> joke. :-) 
> 

I think talking about a swap function is confusing the issue somewhat: you 
don't need to define a swap function in Python because the language 
supports the functionality directly, but that is just hiding the wider 
question of what you do in Python instead of using reference or in/out 
arguments.

The simple answer is that Python makes it easy to return more than result 
from a function, so for every 'out' parameter just return one more result, 
and for a 'ref' parameter just bind that result back to the same name as 
you passed in. Note that this gives you more flexibility than languages 
with 'out' or 'ref' parameters as the caller of the function can decide 
whether to overwrite the original name or create a new one.

A literal implementation of 'swap' in Python is possible but pretty 
pointless:

 def swap(a, b): return b, a
 ...
 x, y = swap(x, y)

but it makes a lot of sense when you move to functions that actually do 
something useful:

 scheme, netloc, path, parms, query, fragment = urlparse(url)

and there's even a convention for ignoring results we don't care about:

 head, _, tail = line.partition(':')



-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list