Rebinding 0 (was Re: "?:", "a and b or c" or "iif")

Neel Krishnaswami neelk at brick.cswv.com
Thu May 27 19:29:46 EDT 1999


In article <000001bea7ee$3a542280$459e2299 at tim>,
Tim Peters <tim_one at email.msn.com> wrote:
>
>If the revolting "(x and [a] ..." got popular, a peephole optimizer could
>get rid of the list ops -- but only at the cost of frustrating Michael and
>Neel's attempts to change what the generated code maps "0" to <0.9 wink>.

How *would* you rebind 0 without hacking the parser?

This currently works for legal variable identifiers:

>>> x
Traceback (innermost last):
  File "<stdin>", line 1, in ?
NameError: x
>>> globals()['x'] = 3
>>> x
3

IOW, the dictionary returned by globals() is the actual global symbol
table used by the Python interpreter.

And since the dictionary returned by globals is just an ordinary
dictionary, it follows that it's possible to bind values to the name
0, for example:

>>> globals()[0] = 3
>>> globals()[0]
3

However, the literal 0 is not being looked up in the global symbol
table; instead, it's parsed and converted to a literal number, so
assigning to the symbol 0 doesn't rebind the literal 0:

>>> 0
0
>>> 0+7
7

Now, I'm not asking this simply to prove my bad character, but because
I am thinking that this might make it simpler to implement a macro
system for Python (in Python, preferably). By that I don't mean a
simple text preprocessor like C's, but an honest-to-god hygienic macro
facility, because I could create symbols and manipulate symbols that
aren't legal Python identifiers.  (And then all I need are
continuations, and I'll be happy. Honest.)

If it does take hacking the parser, where should I begin playing
around to learn how to change things? It looks like I can simply edit
the file Grammar/Grammar, but what else do I need to change? (I'm
thinking of altering Python to have block delimiters as a test
project.)


Neel




More information about the Python-list mailing list