Passing expressions to functions?

前端 未结 6 469

I\'m not quite sure what I mean here, so please bear with me..

In SQLAlchemy, it appears I\'m supposed to pass an expression to filter() in certain cases. When I try to

6条回答
  •  一生所求
    2021-02-01 20:32

    You can't. The expression 5 == 5 is evaluated and only then is the result passed to someFunc. The function just gets True (the True object, to be precise), no matter what the expression was.

    Edit: Concerning your edit, this question is kind of close.

    Edit 2: You could just pass the expression as a string and use eval, like this:

    >>> def someFunc(expression_string):
    ...    print(expression_string, "evaluates to", eval(expression_string))
    
    >>> someFunc("5 == 5")
    5 == 5 evaluates to True
    

    Don't know whether that helps you. Keep in mind that eval is a powerful tool, so it's dangerous to pass arbitrary (and possibly even user-generated) input to it.

提交回复
热议问题