Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map comparison operators to function call

Tags:

python

I'm building a DSL for form validation in Python, and one of the requirements is to be able to specify that a field should 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?

like image 973
Daniel Roseman Avatar asked Jul 24 '10 10:07

Daniel Roseman


2 Answers

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.

like image 56
jchl Avatar answered Oct 16 '22 23:10

jchl


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.

like image 43
Ned Batchelder Avatar answered Oct 17 '22 00:10

Ned Batchelder