Python Interpreter with 2 lines of code!
Learn how to create an interpreter in python!
Did you know you can create a basic Python interpreter with just two lines of code?
Well now you do!
Hi, my name is CyCoderX and in this article, I will demonstrate you how to write a simple Python interpreter using only two lines of code.
This basic interpreter can be a powerful tool for learning, experimenting, and understanding the fundamentals of how an interpreter works. Whether you’re a beginner looking to understand Python better or a seasoned developer curious about creating your own interpreter, this article is for you.
Let’s dive in!
Interested in more Python content? Don’t worry I got you covered! Feel free to explore some of my lists on medium!
The Interpreter
What we basically want to do is to create an infinite loop that continuously:
- Prompts the user for input.
- Executes the input as Python code.
# interpreter.py
while True:
exec(input('>>> '))These lines might look simple, but they pack a lot of functionality. Here’s a detailed breakdown of what each part does:
The while True Loop
The while True statement creates an infinite loop. This loop will continue to run until it is explicitly stopped, which makes it perfect for creating an interactive interpreter that waits for user input indefinitely.
- Infinite Loop: The loop will keep running without terminating on its own.
- Interactive Environment: This setup allows the interpreter to continuously accept and execute user input.
The exec(input('>>> ')) Statement
This line combines two powerful Python functions: input() and exec().
Get CyCoderX’s stories in your inbox
Join Medium for free to get updates from this writer.
input('>>> '):
- Prompting the User: The
input()function displays a prompt ('>>> ') and waits for the user to type a command. - Capturing Input: Once the user types a command and presses Enter, the
input()function returns the entered text as a string.
exec():
- Executing Code: The
exec()function takes a string of Python code and executes it. This means whatever valid Python code the user types at the prompt will be executed immediately. - Dynamic Execution:
exec()can execute any Python statement, including assignments, function definitions, loops, and more.
When combined, exec(input('>>> ')) effectively creates a Read-Eval-Print Loop (REPL):
- Read: Reads the user input.
- Eval: Evaluates (executes) the input as Python code.
- Print: Prints the output or any errors resulting from the execution.
Lets test the code
Here’s a sample interactive session with our two-line interpreter:
>>> 2 + 2
>>> print(2 + 2)
4
>>> x = 5
>>> x
5
>>> print(x * 3)
15
>>> for i in range(3):
... print(i)
...
0
1
2In this session, we:
- Tried a simple addition (
2 + 2) without printing (to see if it will execute but not print anything. - Printed the result of an addition (
print(2 + 2)). - Assigned a value to a variable (
x = 5). - Checked the value of the variable x (to see if it’s going to output 5).
- Printed the result of a multiplication involving the variable (
print(x * 3)). - Used a loop to print numbers from 0 to 2.
This demonstrates that we have successfully built an intepreter!
Use Cases and Applications
This two-line interpreter might be simple, but it has several practical applications:
Learning and Experimenting with Python Code
- Interactive Learning: New learners can experiment with Python commands and see immediate results.
- Quick Testing: Developers can quickly test snippets of code without writing a full script.
Creating a Simple REPL Environment
- Educational Tool: Ideal for teaching programming concepts interactively.
- Prototyping: Useful for rapid prototyping and exploring ideas.
Safety Considerations
While the exec() function is powerful, it can also be dangerous if not used carefully. Here are some potential risks and best practices:
Potential Risks
- Security Risks:
exec()can execute arbitrary code, which might include malicious commands. - Unintended Consequences: Executing code from untrusted input can lead to unpredictable behavior.
Best Practices for Safe Usage
- Restrict Input: Validate and sanitize input before execution.
- Use with Caution: Avoid using
exec()in production code where security is a concern.
Example of Safe Usage
Here’s a simple way to restrict the types of commands that can be executed:
allowed_commands = {'print', 'range'}
while True:
user_input = input('>>> ')
command = user_input.split('(')[0]
if command in allowed_commands:
exec(user_input)
else:
print("Command not allowed")This example restricts the interpreter to only allow print and range commands.
Conclusion
In just two lines of code, we’ve created a simple yet powerful Python interpreter. This basic interpreter is a great tool for learning, experimenting, and understanding the fundamentals of how an interpreter works. While it has its limitations and potential risks, with careful use, it can be an invaluable educational tool.
Happy coding!
Apparently the code I have created demonstrates a simple REPL (Read-Eval-Print Loop). Using Python’s exec() function, it is important to note that this does not constitute a full Python interpreter. A true interpreter involves complex processes such as parsing, compiling, and executing code, along with error handling and memory management. This example serves as a basic tool for executing Python commands interactively, rather than a comprehensive interpreter.
Final Words:
Thank you for taking the time to read my article.
This article was first published on medium by CyCoderX.
Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!
Join me as we explore the exciting world of tech, data and beyond!
For similar articles and updates, feel free to explore my Medium profile
If you enjoyed this article, consider following for future updates.
Interested in Python content and tips? Click here to check out my list on Medium.
Interested in more SQL, Databases and Data Engineering content? Click here to find out more!
What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io









