Skip to content

Instantly share code, notes, and snippets.

@isidentical
Last active March 5, 2019 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isidentical/cc9ad1de447da444f80e6c8cca2dcb97 to your computer and use it in GitHub Desktop.
Save isidentical/cc9ad1de447da444f80e6c8cca2dcb97 to your computer and use it in GitHub Desktop.
import parser
import math
class Function:
def __init__(self, expr):
self.code = parser.expr(expr).compile()
def __call__(self, **kwargs):
return eval(self.code, {'pi': math.pi, 'e': math.e, 'cos': math.cos}, kwargs)
f = Function('2*x')
assert f(x=2) == 4
assert f(x=-2) == -4
g = Function('3*x+2*y+5*z')
assert g(x=1, y=1, z=1) == 10
h = Function('cos(3*pi+x)')
assert h(x=1) == math.cos((3*math.pi)+1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment