-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.py
More file actions
85 lines (76 loc) · 2.37 KB
/
util.py
File metadata and controls
85 lines (76 loc) · 2.37 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# The library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# (c) Sam Burden, UC Berkeley, 2013
import copy
class Lambda(object):
"""
Lambda lambda-like class
Acts like a lambda function, but its string representation
is Python code that yields the object when executed.
>>> f = Lambda('x : x**2')
>>> f(1.41)
1.9880999999999998
>>> g = eval(str(f))
>>> g(2.82)
7.952399999999999
>>> f = Lambda('lambda x,y : x + y')
>>> f(2,-0.1)
1.8999999999999999
"""
def __init__(self, lam):
if not lam.strip().startswith('lambda'):
lam = 'lambda '+lam
self.lam = lam
self.op = eval(lam)
def __call__(self, *args):
return self.op(*args)
def __repr__(self):
return 'Lambda("'+self.lam+'")'
class Struct(object):
"""
Struct struct-like class
Acts like a dict, but keys are members of the object.
>>> a = Struct(foo='bar', goo=7)
>>> b = a.copy()
>>> b.hoo = [1,2,3]
>>> print a
{'goo': 7, 'foo': 'bar'}
>>> print b
{'hoo': [1, 2, 3], 'goo': 7, 'foo': 'bar'}
>>> c = eval(str(a))
>>> a.ioo = []
>>> print a
{'ioo': [], 'goo': 7, 'foo': 'bar'}
>>> print c
{'goo': 7, 'foo': 'bar'}
"""
def __init__( self, file=None, **kwds ):
if file:
self.__dict__.update( eval( open(file).read() ) )
self.__dict__.update( kwds )
def copy( self ):
return Struct(**copy.deepcopy(self.__dict__))
def read( self, file, globals={"__builtins__":None}, locals={} ):
#s = open(file).read()
#for k in subs.keys():
# s = s.replace( k, subs[k] )
self.__dict__.update( eval( open(file).read(), globals, locals ) )
def write( self, file ):
open(file,'w').write(str(self))
def __repr__( self ):
return str( self.__dict__ )
def __getstate__(self):
return self.__dict__
def __setstate__( self, kwds ):
self.__dict__.update( kwds )
if __name__ == "__main__":
import doctest
doctest.testmod()