I need to pass inequalities to a function for evaluation within the function. Is there a way to evaluation the inequality if passed as a string? Or must I pass a representation of the inequality and use if/else statements to generate the sign?
Share
Your question is a little vague, but it sounds like you want to evaluate a string containing an expression (such as
x > 5). Rather than doing that, which is unnecessarily complex, and potentially a security hazard, just define a function, either in the conventional way or using lambda.or
These are both equivalent; now you can pass around
gt5however you like, and when the time comes, you simply call itAs Gerrat’s answer suggests, the operator module may also be useful for things like this.
Now that I know you are processing user strings, I would definitely suggest creating a dictionary that maps strings to functions. (Perhaps that’s what you meant in your title?) Passing userland strings into
getattrseems bad in a number of ways. What happens if you want to add a string that doesn’t correspond to an attribute ofoperator? What happens if the user passes in a string corresponding to a private attribute? Better to create a custom dictionary mapping strings to functions. A dict allows you to specify just those strings you want to accept.You could still save yourself work by using
getattr+operatorto build the dict from a list of strings that you want to accept. Something like:Then update
func_dictlike so:From there you can easily call functions in the dict like so: