autoincrementing

Alex Martelli aleax at aleax.it
Tue Feb 25 13:55:07 EST 2003


Lulu of the Lotus-Eaters wrote:
   ...
> Not ALL rebinding of names is in statements, e.g.
> 
>     >>> x = 3
>     >>> somevar = globals().__setitem__('x',4)
>     >>> x
>     4

Qualified names can of course be re-bound within an expression
(by setattr on the object containing the name, or sometimes by
more devious means).  And since simple global names map to
attributes of sys.modules[__name__], then rebinding such
attributes (by any of various expressions) does have the side
effect of rebinding "global" simple names [pop quiz: in what
case does the same apply to *local* simple names that are not
global names?].  So a more careful way of putting things may
be: no expression-level (non-statement) operation on a name 
ever specifically causes that name to be re-bound (although it
MAY cause side effects that HAPPEN to rebind it: e.g, in your 
example, start with x='x' and use x rather than 'x' as the 
first argument to __setitem__).

> Of course, I don't recommend trying this sort of abomination at home.

When you consider that any call to a function or method may
have almost arbitrary effects, depending only on how that method
or function is coded; and that the call itself is an expression
level (non-statement) operation; then there is no abomination
needed for weird re-bindings to occur.  One could say that this
is because the implementation of the function or method being
called does execute statements, but this need not be the case --
at least, not necessarily for _Python_ statements, as said
implementation might be in C or other language, and it might
call functions in the Python/C API.

Trying to find a way to express this that is safe from quibbles
of this nature is pretty hard.  The concept is that there is no
operator, such that applying that operator to _ANY_ name
causes that _ONE_ name to be re-bound -- to concoct rebindings
one goes through strings (such as 'x' above) -- but such
strings might be the values of the names (the x='x' quibble)
whence the need to specify that there is no _general_ case of
the kind, even though a special combination of a name and its
value may be envisaged that might, by happenstance, cause the
rebinding in question.

Consider an analogy: if I say

  "Paul" has four letters, but Paul does not have four letters

I _might_ be asserting a falsehood in a specific case, as there
MIGHT be an individual named Paul who DOES happen to have four
letters (having just received them in the mail, perhaps).  This
does not mean that the distinction between the individual Paul
and the name "Paul" is worthless -- it just forces one to
express such a distinction verbosely, painstakingly, and
boringly, rather than pithily, concisely and memorably, if and
when one moves in highly quibble-prone cicles...;-)


Alex





More information about the Python-list mailing list