Python meta-circular appraiser

It is not uncommon for an intro programming class to write a Lisp metacircular evaluator. Have there been attempts to do this for Python?

Yes, I know that the structure and syntax of Lisp lends itself perfectly to a metacircular evaluator, etc. etc. Python is likely to be more complex. I'm just wondering if such an attempt was made.

+5
source share
2 answers

For those who don't know what a meta-circular appraiser is, this is an interpreter that is written in a language that needs to be interpreted. For example: a Lisp interpreter written in Lisp, or, in our case, a Python interpreter written in Python. For more information, read this chapter from SICP .

As JBernardo said , PyPy is one. However, the PyPy Python interpreter is a meta-circular evaluator that is implemented in a statically typed subset of Python called RPython .

You will be pleased to know that from version 1.5 PyPy fully complies with the official Python 2.7 specification. Especially: PyPy almost always surpasses Python in performance tests.

. PyPy docs PyPy extra docs.

+7

, :

"""
Metacircular Python interpreter with macro feature.
By Cees Timmerman, 14aug13.
"""

import re
re_macros = re.compile("^#define (\S+) ([^\r\n]+)", re.MULTILINE)

def meta_python_exec(code):
    # Optional meta feature.
    macros = re_macros.findall(code)
    code = re_macros.sub("", code)
    for m in macros:
        code = code.replace(m[0], m[1])

    # Run the code.
    exec(code)

if __name__ == "__main__":
    #code = open("metacircular_overflow.py", "r").read()  # Causes a Qaru in Python 3.2.3, but simply raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" in Python 2.7.3.
    code = "#define 1 2\r\nprint(1 + 1)"
    meta_python_exec(code)
0

All Articles