DEV Community

sma
sma

Posted on • Edited on

1

Lets build a simple interpreter from scratch in python, pt.05: Defining variables

In this post we are defining variables and using them:

class Interpreter:

    # Modified constructor: scope is list of dicts
    # First dict holds global variables, 
    # Last dict holds called function's scope variables

    def __init__(self):
        self.scope=[{}]

    # ....(previous code).... 

    # When we call Set we always create or update variable
    # in last scope: 

    def Set(self,xs):
        _, key, val = xs
        self.scope[-1][key] = self.eval(val)

    # When we call Get we first look into last scope(function scope),
    # if variable is not found then we look into first scope(globals)    
    def Get(self,xs):
        _, var = xs
        if var in self.scope[-1]:
            return self.scope[-1][var]
        elif var in self.scope[0]:
            return self.scope[0][var]
        raise Exception("error: variable not found: "+var)


code=[

    ["Set","answer",  ["Mul",6, 7],  ],
    ["Print", "Answer is: ", ["Get", "answer"] ]
]

interpreter=Interpreter()

interpreter.run(code)
Enter fullscreen mode Exit fullscreen mode

Output:

Answer is: 42
Enter fullscreen mode Exit fullscreen mode

Part 6: While loop

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more