💻 Programming

Interpreter

Interpreter

A program that executes source code line by line. Python, JavaScript.

📖 Detailed Explanation

An interpreter is a program that reads source code written in a programming language line by line and executes it immediately. Unlike a compiler, which translates the entire code into machine code in advance, an interpreter interprets the code at execution time, so a program can be run right away without a separate build process.

The greatest advantage of an interpreter is development speed. When you modify the code, you can check the result immediately, which makes prototyping and debugging fast. Scripting languages such as Python, JavaScript, Ruby, and PHP adopt the interpreter approach and provide high productivity.

Modern interpreters have greatly improved performance by combining JIT (Just-In-Time) compilation techniques instead of pure line-by-line interpretation. For example, V8 (JavaScript) and PyPy (Python) compile frequently executed code into native code at runtime, achieving performance close to that of compiled languages.

In the AI field, interpreted languages are essential for data analysis and model experimentation. The reason Python became the standard language for AI/ML is also the interpreter's fast experimentation cycle, and in interactive environments such as Jupyter Notebook, you can run code cell by cell and check the results, which makes it ideal for exploratory data analysis.

💻 Code Example

# 간단한 인터프리터 구현 예제 (수식 계산기)
class SimpleInterpreter:
    """
    기본 사칙연산을 처리하는 인터프리터
    예: "3 + 5 * 2" -> 13
    """
    def __init__(self, text):
        self.text = text
        self.pos = 0
        self.current_token = None

    def tokenize(self):
        """소스 코드를 토큰으로 분리 (Lexical Analysis)"""
        tokens = []
        i = 0
        while i < len(self.text):
            char = self.text[i]
            if char.isspace():
                i += 1
                continue
            elif char.isdigit():
                num = ''
                while i < len(self.text) and self.text[i].isdigit():
                    num += self.text[i]
                    i += 1
                tokens.append(('NUMBER', int(num)))
            elif char in '+-*/':
                tokens.append(('OP', char))
                i += 1
            else:
                raise SyntaxError(f"알 수 없는 문자: {char}")
        return tokens

    def parse_and_eval(self, tokens):
        """토큰을 파싱하고 실행 (Parsing + Evaluation)"""
        # 곱셈/나눗셈 우선 처리
        i = 0
        while i < len(tokens):
            if tokens[i][0] == 'OP' and tokens[i][1] in '*/':
                left = tokens[i-1][1]
                right = tokens[i+1][1]
                result = left * right if tokens[i][1] == '*' else left // right
                tokens = tokens[:i-1] + [('NUMBER', result)] + tokens[i+2:]
            else:
                i += 1

        # 덧셈/뺄셈 처리
        result = tokens[0][1]
        i = 1
        while i < len(tokens):
            if tokens[i][0] == 'OP':
                op = tokens[i][1]
                right = tokens[i+1][1]
                result = result + right if op == '+' else result - right
                i += 2
        return result

    def interpret(self):
        """소스 코드 해석 및 실행"""
        tokens = self.tokenize()
        return self.parse_and_eval(tokens)

# 인터프리터 사용 예시
expressions = ["3 + 5", "10 - 4 * 2", "100 / 5 + 3 * 7"]
for expr in expressions:
    interpreter = SimpleInterpreter(expr)
    result = interpreter.interpret()
    print(f"{expr} = {result}")

# 출력:
# 3 + 5 = 8
# 10 - 4 * 2 = 2
# 100 / 5 + 3 * 7 = 41

🗣️ Say It Like This in Practice

💬 In a Meeting
"I think we should implement this data analysis pipeline in Python. Since it's an interpreted language, we can quickly build a prototype and check the results. We only need to optimize the performance-critical parts with Cython."
💬 In an Interview
"The key difference between an interpreter and a compiler is the time of execution. A compiler converts the entire code into machine code before execution, whereas an interpreter interprets it line by line at runtime. V8, the modern JavaScript engine, combines the advantages of both approaches through JIT compilation."
💬 In a code review
"This part is called repeatedly in a loop, so interpreter overhead can accumulate. Try switching to numpy vector operations, or, if performance really matters, apply numba's @jit decorator."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Assuming interpreted languages are slow

Modern interpreters have greatly improved performance through JIT compilation and optimization techniques. PyPy is on average 7 times faster than CPython, and the V8 JavaScript engine shows performance close to C++.

❌
Overlooking runtime errors

Interpreted languages have no type checking before execution, so errors occur at runtime. Use static type checking tools such as TypeScript (JS) and mypy (Python) to catch bugs before deployment.

✅
Choosing the right tool

Interpreted languages are suitable for rapid development and experimentation, while compiled languages are suitable for high-performance systems. A hybrid approach is effective: build a prototype in Python and extend only the performance bottleneck parts with C/Rust.

🔗 Related Terms

📚 Learn More