Login

FloatField with safe expression parsing

Author:
joelegner
Posted:
March 15, 2010
Language:
Python
Version:
1.1
Tags:
fields forms parser math eval parsing floatfield
Score:
0 (after 0 ratings)

This FloatField replacement allows users to enter math expressions, such as:

4/5 + sqrt(32)

And will evaluate them safely when the field's clean() function is called. In the example above, it will evaluate to a float value of about 6.457.

Reference:

http://lybniz2.sourceforge.net/safeeval.html

The available functions are listed herein. Note that the from future import division causes integer division expressions to be evaluated as floats. For example "1/2" evaluates as 0.5 when it would otherwise have evaluated to 0 (assuming Python 2.X).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from __future__ import division
from django import forms
from math import *

safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
        'de grees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
        'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
        'sqrt', 'tan', 'tanh'] 

safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ]) 
safe_dict['abs'] = abs 

class MathFloatField(forms.FloatField):
    "FloatField which allows math expressions"

    def clean(self, value):
        try:
            return float(eval(value, {"__builtins__":None}, safe_dict))
        except:
            raise forms.ValidationError("Enter a number or math expression")

More like this

  1. math tag by itchyfingrs 4 years ago
  2. RPN template math by durka 6 years, 7 months ago
  3. {% eval %} templatetag-evaluate expressions by diverman 5 years, 6 months ago
  4. Currency Fields with newforms by sago 8 years, 1 month ago
  5. Tamper safe HiddenFields by alexmeisel 6 years, 6 months ago

Comments

Please login first before commenting.