No swap function in Python?
Ben Wolfson
wolfson at uchicago.edu
Thu May 31 18:14:19 EDT 2001
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
>>>
--
Barnabas T. Rumjuggler
(23:18:22) Clock zero: everyone I like is a damn freak
[...]
(23:20:05) Clock zero: I put this small piece of adhesive-backed paper
on my knife which reads "this machine kills fascists"
More information about the Python-list
mailing list