Login

FloatField with safe expression parsing

Author:
joelegner
Posted:
March 15, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.