'How to convert a string to a runnable (unevaluated) function in Python

I have a code creating a string representing vars from my script:

"((((x) * (320)) + ((y) * (270))) + ((z) * (400))) + ((w) * (500))"

My goal is to store (not evaluate) it as a function:

f = ((((x) * (320)) + ((y) * (270))) + ((z) * (400))) + ((w) * (500))

where x, y, z and w are the actual variables in my Python script.

So that it can be dynamically changed with changing one or more of my variables.

Is there a library doing this?



Solution 1:[1]

The other answers are wrong. It's quite possible to lazily evaluate this in python.

>>> create_function=lambda s:lambda:eval(s)
>>> x=2
>>> y=3
>>> create_function('x+y')()
5
>>> z=create_function('x*y')
>>> z()
6

Solution 2:[2]

import re
from typing import List, Any
from dataclasses import dataclass, field

@dataclass
class Database:
    variables: List[str] = field(default_factory=lambda: [])
    expression: str = ''

def store_expression(database: Database, plain_expression: str) -> None:
    variable_regexes = r'[a-z]'
    # you can get the variables as str and store them
    database.variables = re.findall(variable_regexes, plain_expression)
    
    # Then you can replace the equation with {} and store it too
    database.expression = re.sub(r'[a-z]', '{}', plain_expression)

def eval_expression(database: Database) -> Any:
    return eval(
        database.expression.format(
            *database.variables
        )
    )

s = "((((x) * (320)) + ((y) * (270))) + ((z) * (400))) + ((w) * (500))"

in_memory_db = Database()
store_expression(in_memory_db, s)

x = 1
y = 2
z = 3
w = 4

result = eval_expression(in_memory_db)
print(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mous
Solution 2