Python 2.0 parser module bug(?) and a Q

Pearu Peterson pearu at cens.ioc.ee
Thu Dec 28 11:07:03 CET 2000


On 28 Dec 2000, Martin von Loewis wrote:

> Pearu Peterson <pearu at ioc.ee> writes:
> 
> > I have found that parser module may have a bug in its functions tuple2ast
> > or suite.
> 
> Please report bugs on sourceforge.net/projects/python; on this list,
> they might easily be overlooked.

OK, will do.

> > And my question is (not really related to above):
> > 
> >   Is there inverse function for parser.suite? 
> 
> A colleague of mine has an "unparser" module for Python AST; that is
> not (yet) released to the public, and works not (yet) for 2.0. Please
> contact me if you need more details.

Thanks, but I already wrote a simple inverse parser.suite my self.
See the function ast2string below.

Any constructive critisism is welcome!

Thanks,
	Pearu

from types import *
import string
import parser,token

def _asttuple2str(t,indent=[0]):
    if not isinstance(t,TupleType):
        if isinstance(t,StringType):
            return t+' '
        return '' # if line_info=1 in ast2tuple or ast.totuple
    if not isinstance(t[0],TupleType):
        if token.tok_name.has_key(t[0]):
            if token.tok_name[t[0]]=='INDENT':
                indent[0]+=1
                return '\t'
            if token.tok_name[t[0]]=='DEDENT':
                indent[0]-=1
                return '\r'
            if token.tok_name[t[0]]=='NEWLINE':
                return '\n'+indent[0]*'\t'
            if token.tok_name[t[0]]=='ENDMARKER':
                return t[1]
    return string.join(map(_asttuple2str,t[1:]),'')
def asttuple2str(t,tab=4*' '):
    return _asttuple2str(t).replace('\t\r','').replace('\t',tab)
def ast2string(ast):
    return asttuple2str(ast.totuple())





More information about the Python-list mailing list