Passing expressions to functions?

前端 未结 6 470

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:23

    You can achieve your example if you make "op" a function:

    >>> def magic(left, op, right):
    ...     return op(left, right)
    ...
    >>> magic(5, (lambda a, b: a == b), 5)
    True
    >>> magic(5, (lambda a, b: a == b), 4)
    False
    

    This is more Pythonic than passing a string. It's how functions like sort() work.

    Those SQLAlchemy examples with filter() are puzzling. I don't know the internals about SQLAlchemy, but I'm guessing in an example like query.filter(User.name == 'ed') what's going on is that User.name is a SQLAlchemy-specific type, with an odd implementation of the __eq() function that generates SQL for the filter() function instead of doing a comparison. Ie: they've made special classes that let you type Python expressions that emit SQL code. It's an unusual technique, one I'd avoid unless building something that's bridging two languages like an ORM.

提交回复
热议问题