Pythonic way to specify comparison operators?
I am looking for some advice for the most pythonic (readable,
straightforward, etc) way to specify comparison operators for later use in
comparisons (to be executed via javascript). Something like (this is just
one example implementation that comes to mind - there are lots of other
possible formats):
comparisons = (('a', '>', 'b'), ('b', '==', 'c'))
which would later be evaluated like: (EDIT: this actually not how it will
get evaluated. It will be evaluated in Javascript, not python - read on
for details.)
if a > b:
do something...
if b == c:
do another thing...
The context is that I am working on a Django app (ultimately for
distribution as a plugin) which will require users to write comparisons in
whatever syntax I choose (hence the question about making it pythonic).
The comparisons will reference form fields, and will ultimately be
converted to javascript conditional form display. I suppose an example is
in order:
class MyModel(models.Model):
yes_or_no = models.SomeField...choices are yes or no...
why = models.SomeField...text, but only relevant if yes_or_no == yes...
#here i am inventing some syntax...open to suggestions!!
why.show_if = ('yes_or_no','==','yes')
(hand waving...convert MyModel to ModelForm using
model_form_factory()...gather all "field.show_if" conditions in a
dictionary and attach to ModelForm as MyModelForm.conditions or
something...)
Now in a chunk of javascript in a template, each condition in
MyModelForm.condtions will become a function that listens for a change in
the value of a field, and shows or hides another field in response.
Basically (in pseudo-Javascript/Jquery):
when yes_or_no changes...
if (yes_or_no.value == 'yes'){
$('#div that contains *why* field).show(); }
else {
$('#div that contains *why* field).hide(); }
The goal here is to let the end user specify the conditional display logic
in a straightforward, pythonic way inside the model definition (there may
be an option to specify the conditions on the form class instead, which I
think is more "Djangonic"(??), but for my use case they need to go in the
models). Then my plugin behind the scenes turns that into Javascript in a
template. So you get conditional form display without having to write any
Javascript. Since this will be in the hands of python/django developers, I
am looking for suggestions for the most native, comfortable way to specify
those conditions.
No comments:
Post a Comment