-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathrelation.py
More file actions
31 lines (25 loc) · 1.05 KB
/
relation.py
File metadata and controls
31 lines (25 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Relation(object):
# I need a pickable object to pass a function that was defined from a string...
def __init__(self, name, string):
"""
:param name: name of the relation (i.e. function name)
:param string: expression of the function
version 1 : string = "lambda x: 3 * x + 2"
version 2 : string = "def name(x): return 3 * x + 2"
"""
self.name = name
self.string = string
if self.string.strip().startswith('lambda'):
self.fun = eval(self.string)
elif self.string.strip().startswith('def {}('.format(name)):
eval(compile(self.string, '<string>', 'exec'))
self.fun = eval(name)
else:
raise ValueError("could not compile {} ".format(string))
def __getstate__(self):
return self.name, self.string
def __setstate__(self, state):
name, string = state
Relation.__init__(self, name=name, string=string)
def __call__(self, *args, **kwargs):
return self.fun(*args, **kwargs)