Cellmagic that can replace code in jupyter cells

This is a prototype of a cellmagic that replaces code in a cell before its execution.
Cell 1

translation_dict = {
    "🌎": "print('Hello world')",
    "πŸ’―": "100",
}

Cell 2

%%replace $translation_dict
🌎
print(πŸ’― + πŸ’―)

Out

Hello world
200

I think that %%replace $translation_dict can add some aesthetic aspects to the code appearance, and emojis can be a nice mnemonic aid.

My intention is just to share a fun proof of concept, this project is not to be taken too seriously :wink:

Here is the implementation:

from IPython import get_ipython
from IPython.core.magic import Magics, cell_magic, magics_class
from IPython.core import magic_arguments
import ast
import re

def translate(text, translation):
    # from https://stackoverflow.com/a/63230728/6933377
    regex = re.compile('|'.join(map(re.escape, translation)))
    return regex.sub(lambda match: translation[match.group(0)], text)

@magics_class
class MyMagic(Magics):
    @cell_magic
    def replace(self, line, cell):
        self.translation = ast.literal_eval(f"{line}") # eval dict
        new_cell = translate(cell, self.translation)
        self.shell.run_cell(new_cell)

ipy = get_ipython()
ipy.register_magics(MyMagic)
2 Likes