swap function?

Fredrik Lundh fredrik at effbot.org
Sat Nov 18 07:20:59 EST 2000


Donald wrote:
> What's this about slot numbers?  I always assumed that all
> variables are kept in dictionaries.  Care to expound a little
> more on how local variables are stored, or pass along a
> reference if you know of one?

here's a hint:

http://www.python.org/doc/current/ref/execframes.html

    "Whether a name is local or global in a code block is
    determined by static inspection of the source text for
    the code block: in the absence of global statements,
    a name that is bound anywhere in the code block is
    local in the entire code block; all other names are
    considered global"

    "Local names are searched only on the local namespace;
    global names are searched only in the global and built-in
    namespace"

In other words, all members of the local namespace are known
by the compiler.  The CPython implementation takes advantage
of this, and uses integer indexes to access local values.

(CPython actually uses indexes for all variables: for global names
and attributes, the index is used to find the name instead).

> In defining class methods I often use an instance variable
> where a temp local would work as well, just to make debugging
> easier.  But I often wondered whether a local variable would
> be faster, even if the name spaces are the same size.

local variables are much faster.  try timing it.

> Hummm... come to think of it, I guess self.tmp requires 2
> dictionary lookups, while tmp requires only one.  Or am I
> off track here?

you're off by one: self.tmp requires one dictionary lookup ("self"
is found in the local variable array, "tmp" has to be looked up in
the instance dictionary), while "tmp" requires none.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list