开发者

Map comparison operators to function call

I'm building a DSL for form validation in Python, and one of the requirements is to be able to specify that a field sh开发者_高级运维ould be greater than or less than a constant or another field value. As a result, I'm trying to easily map operators like <, >, <= and >= to their equivalent functions in the operator module, so that they can be called during field validation.

I realise I could just create a dictionary to map the operator to the function, but is there a nicer way to do it? Is there any way to access Python's built-in mapping?


As far as I'm aware, there is no built-in dictionary mapping the string ">" to the function operator.lt, etc.

As others have pointed out, the Python interpreter itself does not make use of such a dictionary, since the process of parsing and executing Python code will first translate the character sequence ">" to a token representing that operator, which will then be translated to bytecode, and the result of executing that bytecode will execute the __lt__ method directly, rather than via the operator.lt function.


Python's internal mapping of "<" to __lt__ (and so on) isn't exposed anywhere in the standard library. There's a lot about Python's internals that aren't exposed as a toolkit. I'm not even sure in general how such a mapping would be created. What maps onto __getitem__?

You'll just have to create your own mapping. It shouldn't be difficult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜