1 | #!/usr/bin/env python2
|
2 | """
|
3 | mycpp/examples/containers.py
|
4 | """
|
5 | from __future__ import print_function
|
6 |
|
7 | import os
|
8 | from mycpp.mylib import log, NewDict, iteritems
|
9 | #from mycpp.mylib import StackArray, MakeStackArray
|
10 |
|
11 | from typing import List, Tuple, Dict, Optional, cast
|
12 |
|
13 | gstr = 'foo' # type: str
|
14 | glist_int = [1, 2] # type: List[int]
|
15 | glist_str = ['spam', 'eggs'] # type: List[str]
|
16 |
|
17 | gEmptyDict = {} # type: Dict[str, str]
|
18 | gdict = {'a': 42, 'b': 43} # type: Dict[str, int]
|
19 | gdict_is = {5: 'foo', 6: 'bar', 7: 'spam'} # type: Dict[int, str]
|
20 | gdict_ss = {'foo': 'foo'}
|
21 |
|
22 |
|
23 | def ListDemo():
|
24 | # type: () -> None
|
25 | intlist = [] # type: List[int]
|
26 | intlist.append(1)
|
27 | intlist.append(2)
|
28 | intlist.append(3)
|
29 |
|
30 | local_list = [1, 2]
|
31 | log("local_list = %d", len(local_list))
|
32 |
|
33 | # turned into intlist->set(1, 42)
|
34 | intlist[1] = 42
|
35 | log("len(intlist) = %d", len(intlist))
|
36 |
|
37 | for i in intlist:
|
38 | log("i = %d", i)
|
39 |
|
40 | # Disable step support
|
41 | # for i in intlist[0:len(intlist):2]:
|
42 | # log("stride i = %d", i)
|
43 |
|
44 | log('1? %d', 1 in intlist)
|
45 | log('42? %d', 42 in intlist)
|
46 |
|
47 | del intlist[:]
|
48 | log("len() after del = %d", len(intlist))
|
49 |
|
50 | strlist = [] # type: List[str]
|
51 |
|
52 | strlist.append('a')
|
53 | strlist.append('b')
|
54 | log("len(strlist) = %d", len(strlist))
|
55 | for s in strlist:
|
56 | log("s = %s", s)
|
57 |
|
58 | log('a? %d', 'a' in strlist)
|
59 | log('foo? %d', 'foo' in strlist)
|
60 |
|
61 | log("len(strlist) = %d", len(strlist))
|
62 |
|
63 | x = strlist.pop()
|
64 | log("x = %s", x)
|
65 |
|
66 | # repeat string
|
67 | no_str = None # type: Optional[str]
|
68 | blank = [no_str] * 3
|
69 | log("len(blank) = %d", len(blank))
|
70 |
|
71 |
|
72 | class Point(object):
|
73 |
|
74 | def __init__(self, x, y):
|
75 | # type: (int, int) -> None
|
76 | self.x = x
|
77 | self.y = y
|
78 |
|
79 |
|
80 | def TupleDemo():
|
81 | # type: () -> None
|
82 |
|
83 | t2 = (3, 'hello') # type: Tuple[int, str]
|
84 |
|
85 | # Destructuring
|
86 | myint, mystr = t2
|
87 | log('myint = %d', myint)
|
88 | log('mystr = %s', mystr)
|
89 |
|
90 | # Does this ever happen? Or do we always use destructring?
|
91 | #log('t2[0] = %d', t2[0])
|
92 | #log('t2[1] = %s', t2[1])
|
93 |
|
94 | x = 3
|
95 | if x in (3, 4, 5):
|
96 | print('yes')
|
97 | else:
|
98 | print('no')
|
99 |
|
100 | p = Point(3, 4)
|
101 | if p.x in (3, 4, 5):
|
102 | print('yes')
|
103 | else:
|
104 | print('no')
|
105 |
|
106 | s = 'foo'
|
107 | if s in ('foo', 'bar'):
|
108 | print('yes')
|
109 | else:
|
110 | print('no')
|
111 |
|
112 | log("glist_int = %d", len(glist_int))
|
113 | log("glist_str = %d", len(glist_str))
|
114 |
|
115 |
|
116 | def DictDemo():
|
117 | # type: () -> None
|
118 |
|
119 | # regression
|
120 | #nonempty = {'a': 'b'} # type: Dict[str, str]
|
121 |
|
122 | d = {} # type: Dict[str, int]
|
123 | d['foo'] = 42
|
124 |
|
125 | # TODO: implement len(Dict) and Dict::remove() and enable this
|
126 | if 0:
|
127 | log('len(d) = %d', len(d))
|
128 |
|
129 | del d['foo']
|
130 | log('len(d) = %d', len(d))
|
131 |
|
132 | # TODO: fix this
|
133 | # log("gdict = %d", len(gdict))
|
134 |
|
135 | ordered = NewDict() # type: Dict[str, int]
|
136 | ordered['a'] = 10
|
137 | ordered['b'] = 11
|
138 | ordered['c'] = 12
|
139 | ordered['a'] = 50
|
140 | for k, v in iteritems(ordered):
|
141 | log("%s %d", k, v)
|
142 |
|
143 | # This is a proper type error
|
144 | # withargs = NewDict({'s': 42}) # type: Dict[str, int]
|
145 |
|
146 | log('len gEmptyDict = %d', len(gEmptyDict))
|
147 | log('len gdict = %d', len(gdict))
|
148 | log('len gdict_is = %d', len(gdict_is))
|
149 | log('len gdict_ss = %d', len(gdict_ss))
|
150 |
|
151 | log('gdict["a"] = %d', gdict['a'])
|
152 | log('gdict_is[5] = %s', gdict_is[5])
|
153 | log('gdict_ss["foo"] = %s', gdict_ss['foo'])
|
154 |
|
155 | lit = {'foo': 42, 'bar': 43}
|
156 | log('foo = %d', lit['foo'])
|
157 | if 'bar' in lit:
|
158 | log('bar is a member')
|
159 |
|
160 |
|
161 | def ContainsDemo():
|
162 | # type: () -> None
|
163 |
|
164 | # List
|
165 |
|
166 | x = 4
|
167 | if x in [3, 4, 5]:
|
168 | print('345 yes')
|
169 | else:
|
170 | print('345 no')
|
171 |
|
172 | if x in [3, 5, 7]:
|
173 | print('357 yes')
|
174 | else:
|
175 | print('357 no')
|
176 |
|
177 | # Tuple is optimized
|
178 | x = 4
|
179 | if x in (3, 4, 5):
|
180 | print('tu 345 yes')
|
181 | else:
|
182 | print('tu 345 no')
|
183 |
|
184 | if x in (3, 5, 7):
|
185 | print('tu 357 yes')
|
186 | else:
|
187 | print('tu 357 no')
|
188 |
|
189 | s = "hi"
|
190 | if s in ("hi", "bye"):
|
191 | print('hi yes')
|
192 | else:
|
193 | print('hi no')
|
194 |
|
195 | # BUG FIX: 'not in' had a bug
|
196 | if s not in ("hi", "bye"):
|
197 | print('hi yes')
|
198 | else:
|
199 | print('hi no')
|
200 |
|
201 |
|
202 | class HasDictMember(object):
|
203 | """
|
204 | based on state.Mem
|
205 | """
|
206 |
|
207 | def __init__(self):
|
208 | # type: () -> None
|
209 | self.builtins = NewDict() # type: Dict[str, str]
|
210 |
|
211 | non_member = NewDict() # type: Dict[str, int]
|
212 |
|
213 | def Get(self, k):
|
214 | # type: (str) -> Optional[str]
|
215 | return self.builtins.get(k)
|
216 |
|
217 |
|
218 | def NewDict_test():
|
219 | # type: () -> None
|
220 | """
|
221 | regression test for a few bugs
|
222 | """
|
223 | h = HasDictMember()
|
224 | result = h.Get('foo')
|
225 | if result is not None:
|
226 | print('result %r' % result)
|
227 | else:
|
228 | print('OK: NewDict result is None')
|
229 |
|
230 | # mutation through non-self object
|
231 | h.builtins = NewDict()
|
232 |
|
233 |
|
234 | def run_tests():
|
235 | # type: () -> None
|
236 |
|
237 | NewDict_test()
|
238 | log('')
|
239 |
|
240 | ListDemo()
|
241 | log('')
|
242 | TupleDemo()
|
243 | log('')
|
244 | DictDemo()
|
245 | log('')
|
246 | ContainsDemo()
|
247 | log('')
|
248 |
|
249 | a = [] # type: List[int]
|
250 | a.append(42)
|
251 |
|
252 | if 0:
|
253 | from mycpp import mylib
|
254 | b = mylib.MakeStackArray(int)
|
255 |
|
256 | #b = cast('StackArray[int]', [])
|
257 | b.append(42)
|
258 |
|
259 | # correct type error!
|
260 | #b.append('foo')
|
261 |
|
262 | b.pop()
|
263 |
|
264 | # correct type error!
|
265 | #a = b
|
266 |
|
267 |
|
268 | def run_benchmarks():
|
269 | # type: () -> None
|
270 | n = 1000000
|
271 | i = 0
|
272 | intlist = [] # type: List[int]
|
273 | strlist = [] # type: List[str]
|
274 | while i < n:
|
275 | intlist.append(i)
|
276 | strlist.append("foo")
|
277 | i += 1
|
278 |
|
279 | log('Appended %d items to 2 lists', n)
|
280 |
|
281 |
|
282 | if __name__ == '__main__':
|
283 | if os.getenv('BENCHMARK'):
|
284 | log('Benchmarking...')
|
285 | run_benchmarks()
|
286 | else:
|
287 | run_tests()
|
288 |
|
289 | # vim: sw=4
|