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

Michael Hudson mwh21 at cam.ac.uk
Fri May 28 02:02:15 EDT 1999


neelk at brick.cswv.com (Neel Krishnaswami) writes:

> 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?

Like this:

>>> from bytecodehacks.code_editor import Function
>>> def f(): return 0
...
>>> f=Function(f)
>>> f.func_code.co_consts
[None, 0]
>>> f.func_code.co_consts[1]="cabbage"
>>> f=f.make_function()
>>> f()
'cabbage'
>>> 

Though, to be fair, I don't understand what Tim was on about either...
 
> 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.

You'd need to be careful to get that to work inside a function,
because of the way local variables work. bytecodehacks works on a
rather different level.

[snip]

> 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.)

You should definitely look at bytecodehacks. It has a macro facility
of sorts, though it can't be used to define new syntax.

> 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.)

Hacking the interpreter is an area I haven't entered yet (eugh! C!).

Hav a nice day!
Michael




More information about the Python-list mailing list