Python from Wise Guy's Viewpoint

Terry Reedy tjreedy at udel.edu
Tue Oct 21 13:44:42 EDT 2003


"Frode Vatvedt Fjeld" <frodef at cs.uit.no> wrote in message
news:2hk76ylj39.fsf at vserver.cs.uit.no...
> What this and my other investigations amount to, is that in Python a
> "name" is somewhat like a lisp symbol [1].

This is true in that names are bound to objects rather than
representing a block of memory.

>In particluar, it is an object that has a pre-computed hash-key,

NO.  There is no name type. 'Name' is a grammatical category, with
particular syntax rules, for Python code, just like 'expression',
'statement' and many others.

A name *may* be represented at runtime as a string, as CPython
*sometimes* does.  The implementation *may*, for efficiency, give
strings a hidden hash value attributre, which CPython does.

For even faster runtime 'name lookup' an implementation may represent
names
as slot numbers (indexes) for a hiddem, non-Python array.  CPython
does this (with C pointer arrays) for function locals whenever the
list of locals is fixed at compile time, which is usually.  (To
prevent this optimization, add to a function body something like 'from
mymod import *', if still allowed, that makes the number of locals
unknowable until runtime.)

To learn about generated bytecodes, read the dis module docs and use
dis.dis.
For example:
>>> import dis
>>> def f(a):
...   b=a+1
...
>>> dis.dis(f)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_FAST                0 (a)
          9 LOAD_CONST               1 (1)
         12 BINARY_ADD
         13 STORE_FAST               1 (b)
         16 LOAD_CONST               0 (None)
         19 RETURN_VALUE
This says: load (onto stack) first pointer in local_vars array and
second pointer in local-constants array, add referenced values and
replace operand pointers with pointer to result, store that result
pointer in the second slot of local_vars, load first constant pointer
(always to None), and return.

Who knows what *we* do when we read, parse, and possibly execute
Python code.

Terry J. Reedy






More information about the Python-list mailing list