Scope troubles with a swap function

Joseph Andrew Knapka jknapka at earthlink.net
Fri Aug 10 17:45:47 EDT 2001


"Cris A. Fugate" wrote:
> 
> On Fri, 10 Aug 2001, Joseph Andrew Knapka wrote:
> 
> > Python has perfectly reasonable scoping (local,global,builtin).
> > It merely refuses to allow you access willy-nilly to arbitrary
> > stack frames, which is a good thing IMO. The fact that Tcl
> > requires such hackery in some situations is one of the things
> > I don't like about it (although I like Tcl a lot in general).
> > If you want to give a Python function access to its caller's data,
> > you pass references, not names.
> >
> How do you do that? What kind of data could I access by passing
> references?

[cc'd to c.l.p -- in case I've got this totally wrong someone
can gently point that out :-]

Just pass arguments. All names in Python have values that
are either basic types (eg Integer) or references to objects
(lists, tuples, class instances). This is, incidentally, exactly
the same as the way object references work in Java, IIRC.

So:

def add_to_list(l):
  l.append(42)

l = [1,2,3]
add_to_list(l)
print l

[1,2,3,42]

The reason the "swap" example doesn't work is that all
you can accomplish my rebinding names in a function is to
rebind the local object names, not the names in the caller.
You can modify the underlying objects, but you cannot modify
the names by which the caller sees those objects.

Regards,

-- 
# Joe Knapka
# "You know how many remote castles there are along the
#  gorges? You can't MOVE for remote castles!" - Lu Tze re. Uberwald
# 2nd Lbl A + 1 = 2nd Pause 2nd Prt A



More information about the Python-list mailing list