No swap function in Python?
Michael Hudson
mwh at python.net
Thu May 31 19:28:34 EDT 2001
"Ben Wolfson" <wolfson at uchicago.edu> writes:
> 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
> >>>
>
Bet it doesn't work inside functions (unless you have an import-* or
an exec).
Cheers,
M.
--
please realize that the Common Lisp community is more than 40
years old. collectively, the community has already been where
every clueless newbie will be going for the next three years.
so relax, please. -- Erik Naggum, comp.lang.lisp
More information about the Python-list
mailing list