Have you looked at the eval function? It evaluates any python expression, so it for sure does the second thing you asked for. I did not really understand your first example, so if eval doesn't work I would need some more explanation of what you are trying to do. Hope it helps :)
What I mean, is ast.literal_eval is meant to be a safe version of eval right? Well, take eval, and be able to pass it to it, similar to this:
Python AST Literal Eval
literal_eval("#safe expression e.g. 1*5#")
}) # Should return 12
So the problem with literal_eval is that it only supports literals. Literals are things like writing a number, string, lists or tuples using their respective syntax. However, you are correct in eval being very unsafe.
I found this project which might be useful or work as inspiration, as it is MIT licensed: github.com/danthedeckie/simpleeval
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.