No swap function in Python?
Bjorn Pettersen
BPettersen at NAREX.com
Thu May 31 18:55:48 EDT 2001
> From: Ben Wolfson [mailto:wolfson at uchicago.edu]
> In article <slrn9hd2cs.iiu.scarblac at pino.selwerd.nl>, "Remco Gerlich"
> <scarblac at pino.selwerd.nl> wrote:
> >
> > A swap function is impossible in Python. A function cannot
> rebind names
> > in the caller's namespace. This is why del is a statement and not a
> > function, for instance.
>
> >>> a = 10
> >>> b = 5
> >>> def swap(**d):
> assert len(d) == 2, 'Only swaps two variables!'
> import sys
> loc = sys._getframe(1).f_locals
> k1, k2 = d.keys()
> loc[k1] = d[k2]
> loc[k2] = d[k1]
>
> >>> swap(a=a, b=b)
> >>> print a, b
> 5 10
> >>>
But...
def foo():
a = 10
b = 5
swap(a=a, b=b)
print a,b
foo()
still prints 10 5...
real-locals-aren't-writable'ly y'rs
-- bjorn
More information about the Python-list
mailing list