The Problem
I am defining a template literal in JavaScript that is used to store python code.
Here is the MRE:
const execTemplate = python_code = """${formattedCode}
"""
where formattedCode
can be any python code, for example:
def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
first_20_fib = fibonacci(20)
print(first_20_fib)
Here’s what would happen if the code above was executed:
def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
# Generate the first 20 Fibonacci numbers
first_20_fib = fibonacci(20)
print(first_20_fib)
Research
I have tried both inserting the variable directly as shown, but I have also tried the replace()
method, which does not solve the problem: const executableString = execTemplate.replace("%CODE%", formattedCode.trim());
where %CODE%
is a placeholder in execTemplate
.
Why is this?