HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

A brainfuck interpreter in python 3

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
brainfuckinterpreterpython

Problem

I've been writing a brainfuck interpreter in python 3. It's nothing serious, but I'm trying to make it as good as possible (considering program structure, user experience and etc) for my own learning purpose. Any suggestion is welcomed.

```
"""A brainfuck interpreter written in Python 3.5."""

import argparse

__all__ = ['Brainfuck']

class Brainfuck:
"""Brainfuck interpreter main class."""

def __init__(self, src, debug=False):
"""
Parameters
----------
src: string
Brainfuck code to be evaluated.
debug: bool (optional, default: False)
Pause at '#' and print some status information.

Public attributes
-----------------
output: string
Output of the brainfuck script.
"""
self._cells = [0]
self._cell_ptr = 0

self._src = self._clean(src, debug)
self._src_ptr = 0

self._open_bracket_indexes = []
self._close_bracket_indexes = []
self._pair_brackets()

self.output = ''

self._evaluate()

@property
def _cell_value(self):
return self._cells[self._cell_ptr]

@_cell_value.setter
def _cell_value(self, value):
self._cells[self._cell_ptr] += value

if self._cells[self._cell_ptr] > 255:
self._cells[self._cell_ptr] = 0

elif self._cells[self._cell_ptr] [],.#' if debug else '+-<>[],.'
return ''.join(c for c in src if c in commands)

def _pair_brackets(self):
"""
_open_bracket_indexes[i] is paired with _close_bracket_indexes[i].
"""
stack = []

for index, command in enumerate(self._src):
if command == '[':
stack.append(index)

elif command == ']':
self._open_bracket_indexes.append(stack.pop())
self._close_bracket_indexes.append(index)

def _evaluate(self):
while self._src_ptr ':
self._cell

Solution

Your implementation of the , command, using input('> '), is non-standard. Standard Brainfuck shouldn't print a prompt, nor should it wait for Return to be pressed. Rather, it should just read one byte from sys.stdin.

The condition

while self._src_ptr <= len(self._src)-1:


… would be more idiomatically written as

while self._src_ptr < len(self._src):


Similarly simplify if self._cell_ptr > len(self._cells)-1.

What would you guess that

self._cell_value = 1


does? I find it deceptive that it increments the cell value by 1 (with wraparound) rather than setting the value. I recommend writing it as self._cell_value += 1. Keep the wraparound logic in the setter, if you want.

Code Snippets

while self._src_ptr <= len(self._src)-1:
while self._src_ptr < len(self._src):
self._cell_value = 1

Context

StackExchange Code Review Q#134578, answer score: 2

Revisions (0)

No revisions yet.