code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
# test that no-arg super() works when self is closed over class A: def __init__(self): self.val = 4 def foo(self): # we access a member of self to check that self is correct return list(range(self.val)) class B(A): def foo(self): # self is closed over because it's referenced in the list comprehension # and then super() must detect this and load from the closure cell return [self.bar(i) for i in super().foo()] def bar(self, x): return 2 * x print(A().foo()) print(B().foo())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/class_super_closure.py
Python
apache-2.0
552
# test super with multiple inheritance class A: def foo(self): print('A.foo') class B: def foo(self): print('B.foo') class C(A, B): def foo(self): print('C.foo') super().foo() C().foo()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/class_super_multinherit.py
Python
apache-2.0
234
# Calling object.__init__() via super().__init__ try: # If we don't expose object.__init__ (small ports), there's # nothing to test. object.__init__ except AttributeError: print("SKIP") raise SystemExit class Test(object): def __init__(self): super().__init__() print("Test.__init__") t = Test() class Test2: def __init__(self): super().__init__() print("Test2.__init__") t = Test2()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/class_super_object.py
Python
apache-2.0
448
# check that we can use an instance of B in a method of A class A: def store(a, b): a.value = b class B: pass b = B() A.store(b, 1) print(b.value)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/class_use_other.py
Python
apache-2.0
166
# closures def f(x): y = 2 * x def g(z): return y + z return g print(f(1)(1)) x = f(2) y = f(3) print(x(1), x(2), x(3)) print(y(1), y(2), y(3)) print(x(1), x(2), x(3)) print(y(1), y(2), y(3))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/closure1.py
Python
apache-2.0
215
# closures; closing over an argument def f(x): y = 2 * x def g(z): return x + y + z return g print(f(1)(1)) x = f(2) y = f(3) print(x(1), x(2), x(3)) print(y(1), y(2), y(3)) print(x(1), x(2), x(3)) print(y(1), y(2), y(3))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/closure2.py
Python
apache-2.0
245
# test closure with default args def f(): a = 1 def bar(b = 10, c = 20): print(a + b + c) bar() bar(2) bar(2, 3) print(f())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/closure_defargs.py
Python
apache-2.0
154
# test closure with lots of closed over variables def f(): a, b, c, d, e, f, g, h = [i for i in range(8)] def x(): print(a, b, c, d, e, f, g, h) x() f()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/closure_manyvars.py
Python
apache-2.0
175
# test passing named arg to closed-over function def f(): x = 1 def g(z): print(x, z) return g f()(z=42)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/closure_namedarg.py
Python
apache-2.0
127
print(1 < 2 < 3) print(1 < 2 < 3 < 4) print(1 > 2 < 3) print(1 < 2 > 3)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/compare_multi.py
Python
apache-2.0
72
def f(): # list comprehension print([a + 1 for a in range(5)]) print([(a, b) for a in range(3) for b in range(2)]) print([a * 2 for a in range(7) if a > 3]) print([a for a in [1, 3, 5]]) print([a for a in [a for a in range(4)]]) # dict comprehension d = {a : 2 * a for a in range(5)} print(d[0], d[1], d[2], d[3], d[4]) # set comprehension # see set_comprehension.py f()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/comprehension1.py
Python
apache-2.0
421
# sets, see set_containment for i in 1, 2: for o in {1:2}, {1:2}.keys(): print("{} in {}: {}".format(i, str(o), i in o)) print("{} not in {}: {}".format(i, str(o), i not in o)) haystack = "supercalifragilistc" for needle in [haystack[i:] for i in range(len(haystack))]: print(needle, "in", haystack, "::", needle in haystack) print(needle, "not in", haystack, "::", needle not in haystack) print(haystack, "in", needle, "::", haystack in needle) print(haystack, "not in", needle, "::", haystack not in needle) for needle in [haystack[:i+1] for i in range(len(haystack))]: print(needle, "in", haystack, "::", needle in haystack) print(needle, "not in", haystack, "::", needle not in haystack) print(haystack, "in", needle, "::", haystack in needle) print(haystack, "not in", needle, "::", haystack not in needle) # containment of bytes/ints in bytes print(b'' in b'123') print(b'0' in b'123', b'1' in b'123') print(48 in b'123', 49 in b'123') # containment of int in str is an error try: 1 in '123' except TypeError: print('TypeError') # until here, the tests would work without the 'second attempt' iteration thing. for i in 1, 2: for o in [], [1], [1, 2]: print("{} in {}: {}".format(i, o, i in o)) print("{} not in {}: {}".format(i, o, i not in o))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/containment.py
Python
apache-2.0
1,336
for i in range(4): print('one', i) if i > 2: continue print('two', i) for i in range(4): print('one', i) if i < 2: continue print('two', i) for i in [1, 2, 3, 4]: if i == 3: continue print(i)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/continue.py
Python
apache-2.0
250
# test decorators def dec(f): print('dec') return f def dec_arg(x): print(x) return lambda f:f # plain decorator @dec def f(): pass # decorator with arg @dec_arg('dec_arg') def g(): pass # decorator of class @dec class A: pass
YifuLiu/AliOS-Things
components/py_engine/tests/basics/decorator.py
Python
apache-2.0
260
class C: def f(): pass # del a class attribute del C.f try: print(C.x) except AttributeError: print("AttributeError") try: del C.f except AttributeError: print("AttributeError") # del an instance attribute c = C() c.x = 1 print(c.x) del c.x try: print(c.x) except AttributeError: print("AttributeError") try: del c.x except AttributeError: print("AttributeError") # try to del an attribute of a built-in class try: del int.to_bytes except (AttributeError, TypeError): # uPy raises AttributeError, CPython raises TypeError print('AttributeError/TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_attr.py
Python
apache-2.0
619
def f(): x = 1 y = 2 def g(): nonlocal x print(y) try: print(x) except NameError: print("NameError") def h(): nonlocal x print(y) try: del x except NameError: print("NameError") print(x, y) del x g() h() f()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_deref.py
Python
apache-2.0
352
# del global def do_del(): global x del x x = 1 print(x) do_del() try: print(x) except NameError: print("NameError") try: do_del() except: # NameError: # FIXME uPy returns KeyError for this print("NameError") # delete globals using a list a = 1 del (a,) try: print(a) except NameError: print("NameError") a = 2 b = 3 del (a, b) try: print(a) except NameError: print("NameError") try: print(b) except NameError: print("NameError") a = 1 b = 2 c = 3 del (a, b, c) try: print(a) except NameError: print("NameError") try: print(b) except NameError: print("NameError") try: print(c) except NameError: print("NameError") a = 1 b = 2 c = 3 del (a, (b, c))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_global.py
Python
apache-2.0
732
# delete local then try to reference it def f(): x = 1 y = 2 print(x, y) del x print(y) try: print(x) except NameError: print("NameError"); f() # delete local then try to delete it again def g(): x = 3 y = 4 print(x, y) del x print(y) try: del x except NameError: print("NameError"); g()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_local.py
Python
apache-2.0
377
# del name x = 1 print(x) del x try: print(x) except NameError: print("NameError") try: del x except: # NameError: # FIXME uPy returns KeyError for this print("NameError") class C: def f(): pass
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_name.py
Python
apache-2.0
229
l = [1, 2, 3] print(l) del l[0] print(l) del l[-1] print(l) d = {1:2, 3:4, 5:6} del d[1] del d[3] print(d) del d[5] print(d) # delete nested subscr d = {0:{0:0}} del d[0][0] print(d)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/del_subscr.py
Python
apache-2.0
185
try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit d = deque((), 2) print(len(d)) print(bool(d)) try: d.popleft() except IndexError: print("IndexError") print(d.append(1)) print(len(d)) print(bool(d)) print(d.popleft()) print(len(d)) d.append(2) print(d.popleft()) d.append(3) d.append(4) print(len(d)) print(d.popleft(), d.popleft()) try: d.popleft() except IndexError: print("IndexError") d.append(5) d.append(6) d.append(7) print(len(d)) print(d.popleft(), d.popleft()) print(len(d)) try: d.popleft() except IndexError: print("IndexError") # Case where get index wraps around when appending to full deque d = deque((), 2) d.append(1) d.append(2) d.append(3) d.append(4) d.append(5) print(d.popleft(), d.popleft()) # Negative maxlen is not allowed try: deque((), -1) except ValueError: print("ValueError") # Unsupported unary op try: ~d except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/deque1.py
Python
apache-2.0
1,049
# Tests for deques with "check overflow" flag and other extensions # wrt to CPython. try: try: from ucollections import deque except ImportError: from collections import deque except ImportError: print("SKIP") raise SystemExit # Initial sequence is not supported try: deque([1, 2, 3], 10) except ValueError: print("ValueError") # Not even empty list, only empty tuple try: deque([], 10) except ValueError: print("ValueError") # Only fixed-size deques are supported, so length arg is mandatory try: deque(()) except TypeError: print("TypeError") d = deque((), 2, True) try: d.popleft() except IndexError: print("IndexError") print(d.append(1)) print(d.popleft()) d.append(2) print(d.popleft()) d.append(3) d.append(4) print(d.popleft(), d.popleft()) try: d.popleft() except IndexError as e: print(repr(e)) d.append(5) d.append(6) print(len(d)) try: d.append(7) except IndexError as e: print(repr(e)) print(len(d)) print(d.popleft(), d.popleft()) print(len(d)) try: d.popleft() except IndexError as e: print(repr(e))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/deque2.py
Python
apache-2.0
1,114
# basic dictionary d = {} print(d) d[2] = 123 print(d) d = {1:2} d[3] = 3 print(len(d), d[1], d[3]) d[1] = 0 print(len(d), d[1], d[3]) print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}') x = 1 while x < 100: d[x] = x x += 1 print(d[50]) # equality operator on dicts of different size print({} == {1:1}) # equality operator on dicts of same size but with different keys print({1:1} == {2:1}) # 0 replacing False's item d = {} d[False] = 'false' d[0] = 'zero' print(d) # False replacing 0's item d = {} d[0] = 'zero' d[False] = 'false' print(d) # 1 replacing True's item d = {} d[True] = 'true' d[1] = 'one' print(d) # True replacing 1's item d = {} d[1] = 'one' d[True] = 'true' print(d) # mixed bools and integers d = {False:10, True:11, 2:12} print(d[0], d[1], d[2]) # value not found try: {}[0] except KeyError as er: print('KeyError', er, er.args) # unsupported unary op try: +{} except TypeError: print('TypeError') # unsupported binary op try: {} + {} except TypeError: print('TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict1.py
Python
apache-2.0
1,046
# using strings as keys in dict d = {'1': 1, '2': 2} print(d['1'], d['2']) d['3'] = 3 print(d['1'], d['2'], d['3']) d['2'] = 222 print(d['1'], d['2'], d['3']) d2 = dict(d) print('2' in d2) print(id(d) != id(d2), d == d2)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict2.py
Python
apache-2.0
225
d = {1: 2, 3: 4} print(len(d)) d.clear() print(d) d[2] = 42 print(d)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_clear.py
Python
apache-2.0
69
# dict constructor d = dict() print(d) d = dict({1:2}) print(d) d = dict(a=1) print(d) d = dict({1:2}, a=3) print(d[1], d['a']) d = dict([(1, 2)], a=3, b=4) print(d[1], d['a'], d['b'])
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_construct.py
Python
apache-2.0
190
a = {i: 2*i for i in range(100)} b = a.copy() for i in range(100): print(i, b[i]) print(len(b))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_copy.py
Python
apache-2.0
100
for n in range(20): print('testing dict with {} items'.format(n)) for i in range(n): # create dict d = dict() for j in range(n): d[str(j)] = j print(len(d)) # delete an item del d[str(i)] print(len(d)) # check items for j in range(n): if str(j) in d: if j == i: print(j, 'in d, but it should not be') else: if j != i: print(j, 'not in d, but it should be')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_del.py
Python
apache-2.0
547
# test that fixed dictionaries cannot be modified try: import uerrno except ImportError: print("SKIP") raise SystemExit # Save a copy of uerrno.errorcode, so we can check later # that it hasn't been modified. errorcode_copy = uerrno.errorcode.copy() try: uerrno.errorcode.popitem() except TypeError: print("TypeError") try: uerrno.errorcode.pop(0) except TypeError: print("TypeError") try: uerrno.errorcode.setdefault(0, 0) except TypeError: print("TypeError") try: uerrno.errorcode.update([(1, 2)]) except TypeError: print("TypeError") try: del uerrno.errorcode[1] except TypeError: print("TypeError") try: uerrno.errorcode[1] = 'foo' except TypeError: print("TypeError") try: uerrno.errorcode.clear() except TypeError: print("TypeError") assert uerrno.errorcode == errorcode_copy
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_fixed.py
Python
apache-2.0
860
print(dict([(1, "foo")])) d = dict([("foo", "foo2"), ("bar", "baz")]) print(sorted(d.keys())) print(sorted(d.values())) try: dict(((1,),)) except ValueError: print("ValueError") try: dict(((1, 2, 3),)) except ValueError: print("ValueError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_from_iter.py
Python
apache-2.0
259
d = dict.fromkeys([1, 2, 3, 4]) l = list(d.keys()) l.sort() print(l) d = dict.fromkeys([1, 2, 3, 4], 42) l = list(d.values()) l.sort() print(l)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_fromkeys.py
Python
apache-2.0
145
try: reversed except: print("SKIP") raise SystemExit # argument to fromkeys has no __len__ d = dict.fromkeys(reversed(range(1))) #d = dict.fromkeys((x for x in range(1))) print(d)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_fromkeys2.py
Python
apache-2.0
193
for d in {}, {42:2}: print(d.get(42)) print(d.get(42,2))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_get.py
Python
apache-2.0
65
# check that interned strings are compared against non-interned strings di = {"key1": "value"} # lookup interned string k = "key1" print(k in di) # lookup non-interned string k2 = "key" + "1" print(k == k2) print(k2 in di) # lookup non-interned string print("".join(['k', 'e', 'y', '1']) in di)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_intern.py
Python
apache-2.0
299
d = {1: 2, 3: 4} els = [] for i in d: els.append((i, d[i])) print(sorted(els))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_iterator.py
Python
apache-2.0
83
d = {1: 2, 3: 4} print(d.pop(3), d) print(d) print(d.pop(1, 42), d) print(d.pop(1, 42), d) print(d.pop(1, None), d) try: print(d.pop(1), "!!!") except KeyError: print("Raised KeyError") else: print("Did not raise KeyError!")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_pop.py
Python
apache-2.0
237
els = [] d = {1:2,3:4} a = d.popitem() print(len(d)) els.append(a) a = d.popitem() print(len(d)) els.append(a) try: print(d.popitem(), "!!!",) except KeyError: print("Raised KeyError") else: print("Did not raise KeyError") print(sorted(els))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_popitem.py
Python
apache-2.0
255
d = {} print(d.setdefault(1)) print(d.setdefault(1)) print(d.setdefault(5, 42)) print(d.setdefault(5, 1)) print(d[1]) print(d[5]) d.pop(5) print(d.setdefault(5, 1)) print(d[1]) print(d[5])
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_setdefault.py
Python
apache-2.0
191
# dict object with special methods d = {} d.__setitem__('2', 'two') print(d.__getitem__('2')) d.__delitem__('2') print(d)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_specialmeth.py
Python
apache-2.0
123
d = {1:2, 3:4} print(len(d)) d.update(["ab"]) print(d[1]) print(d[3]) print(d["a"]) print(len(d)) d.update([(1,4)]) print(d[1]) print(len(d)) # using keywords d.update(a=5) print(d['a']) d.update([(1,5)], b=6) print(d[1], d['b'])
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_update.py
Python
apache-2.0
231
d = {1: 2} for m in d.items, d.values, d.keys: print(m()) print(list(m())) # print a view with more than one item print({1:1, 2:1}.values()) # unsupported binary op on a dict values view try: {1:1}.values() + 1 except TypeError: print('TypeError') # unsupported binary op on a dict keys view try: {1:1}.keys() + 1 except TypeError: print('TypeError') # set operations still to come
YifuLiu/AliOS-Things
components/py_engine/tests/basics/dict_views.py
Python
apache-2.0
410
# test equality print(None == None) print(False == None) print(False == False) print(False == True) print(() == ()) print(() == []) print([] == []) print(() == {}) print({} == ()) print(() == None) print(() == False) print(() == print) print([] == None) print([] == False) print([] == print) print({} == None) print({} == False) print({} == print) print(1 == 1) print(1 == 2) print(1 == ()) print(1 == []) print(1 == {}) print(1 == 'a') print('a' == 'a') print('a' == 'ab') print('a' == 1) print('a' == ()) # same as above but with != print(None != None) print(False != None) print(False != False) print(False != True) print(() != ()) print(() != []) print([] != []) print(() != {}) print({} != ()) print(() != None) print(() != False) print(() != print) print([] != None) print([] != False) print([] != print) print({} != None) print({} != False) print({} != print) print(1 != 1) print(1 != 2) print(1 != ()) print(1 != []) print(1 != {}) print(1 != 'a') print('a' != 'a') print('a' != 'ab') print('a' != 1) print('a' != ())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/equal.py
Python
apache-2.0
1,043
# test equality for classes/instances to other types class A: pass class B: pass class C(A): pass print(A == None) print(None == A) print(A == A) print(A() == A) print(A() == A()) print(A == B) print(A() == B) print(A() == B()) print(A == C) print(A() == C) print(A() == C())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/equal_class.py
Python
apache-2.0
295
# test errno's and uerrno module try: import uerrno except ImportError: print("SKIP") raise SystemExit # check that constants exist and are integers print(type(uerrno.EIO)) # check that errors are rendered in a nice way msg = str(OSError(uerrno.EIO)) print(msg[:7], msg[-5:]) msg = str(OSError(uerrno.EIO, "details")) print(msg[:7], msg[-14:]) msg = str(OSError(uerrno.EIO, "details", "more details")) print(msg[:1], msg[-28:]) # check that unknown errno is still rendered print(str(OSError(9999))) # this tests a failed constant lookup in errno errno = uerrno print(errno.__name__)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/errno1.py
Python
apache-2.0
600
# test exception matching against a tuple try: fail except (Exception,): print('except 1') try: fail except (Exception, Exception): print('except 2') try: fail except (TypeError, NameError): print('except 3') try: fail except (TypeError, ValueError, Exception): print('except 4')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/except_match_tuple.py
Python
apache-2.0
316
# test basic properties of exceptions print(repr(IndexError())) print(str(IndexError())) print(str(IndexError("foo"))) a = IndexError(1, "test", [100, 200]) print(repr(a)) print(str(a)) print(a.args) s = StopIteration() print(s.value) s = StopIteration(1, 2, 3) print(s.value) print(OSError().errno) print(OSError(1, "msg").errno)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/exception1.py
Python
apache-2.0
336
# Exception chaining is not supported, but check that basic # exception works as expected. try: raise Exception from None except Exception: print("Caught Exception")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/exception_chain.py
Python
apache-2.0
174
try: raise ArithmeticError except Exception: print("Caught ArithmeticError via Exception") try: raise ArithmeticError except ArithmeticError: print("Caught ArithmeticError") try: raise AssertionError except Exception: print("Caught AssertionError via Exception") try: raise AssertionError except AssertionError: print("Caught AssertionError") try: raise AttributeError except Exception: print("Caught AttributeError via Exception") try: raise AttributeError except AttributeError: print("Caught AttributeError") try: raise EOFError except Exception: print("Caught EOFError via Exception") try: raise EOFError except EOFError: print("Caught EOFError") try: raise Exception except BaseException: print("Caught Exception via BaseException") try: raise Exception except Exception: print("Caught Exception") try: raise ImportError except Exception: print("Caught ImportError via Exception") try: raise ImportError except ImportError: print("Caught ImportError") try: raise IndentationError except SyntaxError: print("Caught IndentationError via SyntaxError") try: raise IndentationError except IndentationError: print("Caught IndentationError") try: raise IndexError except LookupError: print("Caught IndexError via LookupError") try: raise IndexError except IndexError: print("Caught IndexError") try: raise KeyError except LookupError: print("Caught KeyError via LookupError") try: raise KeyError except KeyError: print("Caught KeyError") try: raise LookupError except Exception: print("Caught LookupError via Exception") try: raise LookupError except LookupError: print("Caught LookupError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/exceptpoly.py
Python
apache-2.0
1,769
try: raise MemoryError except Exception: print("Caught MemoryError via Exception") try: raise MemoryError except MemoryError: print("Caught MemoryError") try: raise NameError except Exception: print("Caught NameError via Exception") try: raise NameError except NameError: print("Caught NameError") try: raise NotImplementedError except RuntimeError: print("Caught NotImplementedError via RuntimeError") try: raise NotImplementedError except NotImplementedError: print("Caught NotImplementedError") try: raise OSError except Exception: print("Caught OSError via Exception") try: raise OSError except OSError: print("Caught OSError") try: raise OverflowError except ArithmeticError: print("Caught OverflowError via ArithmeticError") try: raise OverflowError except OverflowError: print("Caught OverflowError") try: raise RuntimeError except Exception: print("Caught RuntimeError via Exception") try: raise RuntimeError except RuntimeError: print("Caught RuntimeError") try: raise SyntaxError except Exception: print("Caught SyntaxError via Exception") try: raise SyntaxError except SyntaxError: print("Caught SyntaxError") try: raise TypeError except Exception: print("Caught TypeError via Exception") try: raise TypeError except TypeError: print("Caught TypeError") try: raise ValueError except Exception: print("Caught ValueError via Exception") try: raise ValueError except ValueError: print("Caught ValueError") try: raise ZeroDivisionError except ArithmeticError: print("Caught ZeroDivisionError via ArithmeticError") try: raise ZeroDivisionError except ZeroDivisionError: print("Caught ZeroDivisionError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/exceptpoly2.py
Python
apache-2.0
1,789
# check modulo matches python definition # This tests compiler version print(123 // 7) print(-123 // 7) print(123 // -7) print(-123 // -7) a = 10000001 b = 10000000 print(a // b) print(a // -b) print(-a // b) print(-a // -b)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/floordivide.py
Python
apache-2.0
227
# check modulo matches python definition a = 987654321987987987987987987987 b = 19 print(a // b) print(a // -b) print(-a // b) print(-a // -b) a = 10000000000000000000000000000000000000000000 b = 100 print(a // b) print(a // -b) print(-a // b) print(-a // -b)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/floordivide_intbig.py
Python
apache-2.0
262
# basic for loop def f(): for x in range(2): for y in range(2): for z in range(2): print(x, y, z) f() # range with negative step for i in range(3, -1, -1): print(i) a = -1 # range with non-constant step - we optimize constant steps, so this # will be executed differently for i in range(3, -1, a): print(i)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for1.py
Python
apache-2.0
359
i = 'init' for i in range(0): pass print(i) # should not have been modified for i in range(10): pass print(i) # should be last successful value of loop
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for2.py
Python
apache-2.0
161
# test assigning to iterator within the loop for i in range(2): print(i) i = 2 # test assigning to range parameter within the loop # (since we optimise for loops, this needs checking, currently it fails) n = 2 for i in range(n): print(i) n = 0
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for3.py
Python
apache-2.0
261
# Testcase for break in a for [within bunch of other code] # https://github.com/micropython/micropython/issues/635 def foo(): seq = [1, 2, 3] v = 100 i = 5 while i > 0: print(i) for a in seq: if a == 2: break i -= 1 foo() # break from within nested for loop def bar(): l = [1, 2, 3] for e1 in l: print(e1) for e2 in l: print(e1, e2) if e2 == 2: break bar()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for_break.py
Python
apache-2.0
493
# test for-else statement # test optimised range with simple else for i in range(2): print(i) else: print('else') # test optimised range with break over else for i in range(2): print(i) break else: print('else') # test nested optimised range with continue in the else for i in range(4): print(i) for j in range(4): pass else: continue break # test optimised range with non-constant end value N = 2 for i in range(N): print(i) else: print('else') # test generic iterator with simple else for i in [0, 1]: print(i) else: print('else') # test generic iterator with break over else for i in [0, 1]: print(i) break else: print('else')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for_else.py
Python
apache-2.0
716
# test for+range, mostly to check optimisation of this pair # apply args using * for x in range(*(1, 3)): print(x) for x in range(1, *(6, 2)): print(x) # zero step try: for x in range(1, 2, 0): pass except ValueError: print('ValueError') # apply args using ** try: for x in range(**{'end':1}): print(x) except TypeError: print('TypeError') try: for x in range(0, **{'end':1}): print(x) except TypeError: print('TypeError') try: for x in range(0, 1, **{'step':1}): print(x) except TypeError: print('TypeError') # keyword args try: for x in range(end=1): print(x) except TypeError: print('TypeError') try: for x in range(0, end=1): print(x) except TypeError: print('TypeError') try: for x in range(start=0, end=1): print(x) except TypeError: print('TypeError') try: for x in range(0, 1, step=1): print(x) except TypeError: print('TypeError') # argument is a comprehension try: for x in range(0 for i in []): print(x) except TypeError: print('TypeError') try: for x in range(0, (0 for i in [])): print(x) except TypeError: print('TypeError') try: for x in range(0, 1, (0 for i in [])): print(x) except TypeError: print('TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for_range.py
Python
apache-2.0
1,318
# test returning from within a for loop def f(): for i in [1, 2, 3]: return i print(f())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/for_return.py
Python
apache-2.0
103
# basic sets try: frozenset except NameError: print("SKIP") raise SystemExit s = frozenset() print(s) s = frozenset({1}) print(s) s = frozenset({3, 4, 3, 1}) print(sorted(s)) # frozensets are hashable unlike sets print({frozenset("1"): 2})
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset1.py
Python
apache-2.0
257
try: frozenset except NameError: print("SKIP") raise SystemExit s = frozenset({1, 2, 3, 4}) try: print(s.add(5)) except AttributeError: print("AttributeError") try: print(s.update([5])) except AttributeError: print("AttributeError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset_add.py
Python
apache-2.0
263
try: frozenset except NameError: print("SKIP") raise SystemExit sets = [ frozenset(), frozenset({1}), frozenset({1, 2}), frozenset({1, 2, 3}), frozenset({2, 3}), frozenset({2, 3, 5}), frozenset({5}), frozenset({7}) ] for s in sets: for t in sets: print(sorted(s), '|', sorted(t), '=', sorted(s | t)) print(sorted(s), '^', sorted(t), '=', sorted(s ^ t)) print(sorted(s), '&', sorted(t), '=', sorted(s & t)) print(sorted(s), '-', sorted(t), '=', sorted(s - t)) u = s.copy() u |= t print(sorted(s), "|=", sorted(t), '-->', sorted(u)) u = s.copy() u ^= t print(sorted(s), "^=", sorted(t), '-->', sorted(u)) u = s.copy() u &= t print(sorted(s), "&=", sorted(t), "-->", sorted(u)) u = s.copy() u -= t print(sorted(s), "-=", sorted(t), "-->", sorted(u)) print(sorted(s), '==', sorted(t), '=', s == t) print(sorted(s), '!=', sorted(t), '=', s != t) print(sorted(s), '>', sorted(t), '=', s > t) print(sorted(s), '>=', sorted(t), '=', s >= t) print(sorted(s), '<', sorted(t), '=', s < t) print(sorted(s), '<=', sorted(t), '=', s <= t)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset_binop.py
Python
apache-2.0
1,227
try: frozenset except NameError: print("SKIP") raise SystemExit s = frozenset({1, 2, 3, 4}) t = s.copy() print(type(t)) for i in s, t: print(sorted(i))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset_copy.py
Python
apache-2.0
169
try: frozenset except NameError: print("SKIP") raise SystemExit l = [1, 2, 3, 4] s = frozenset(l) outs = [s.difference(), s.difference(frozenset({1})), s.difference(frozenset({1}), [1, 2]), s.difference(frozenset({1}), {1, 2}, {2, 3})] for out in outs: print(type(out), sorted(out)) s = frozenset(l) try: print(s.difference_update({1})) except AttributeError: print("AttributeError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset_difference.py
Python
apache-2.0
434
try: frozenset except NameError: print("SKIP") raise SystemExit # Examples from https://docs.python.org/3/library/stdtypes.html#set # "Instances of set are compared to instances of frozenset based on their # members. For example:" print(set('abc') == frozenset('abc')) # This doesn't work in uPy #print(set('abc') in set([frozenset('abc')]))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/frozenset_set.py
Python
apache-2.0
355
# calling a function def f(): print(1) f()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun1.py
Python
apache-2.0
48
# calling a function from a function def f(x): print(x + 1) def g(x): f(2 * x) f(4 * x) g(3)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun2.py
Python
apache-2.0
108
# function with large number of arguments def fun(a, b, c, d, e, f, g): return a + b + c * d + e * f * g print(fun(1, 2, 3, 4, 5, 6, 7))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun3.py
Python
apache-2.0
143
def foo(x: int, y: list) -> dict: return {x: y} print(foo(1, [2, 3]))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_annotations.py
Python
apache-2.0
75
# test calling a function with keywords given by **dict def f(a, b): print(a, b) f(1, **{'b':2}) f(1, **{'b':val for val in range(1)}) try: f(1, **{len:2}) except TypeError: print('TypeError') # test calling a method with keywords given by **dict class A: def f(self, a, b): print(a, b) a = A() a.f(1, **{'b':2}) a.f(1, **{'b':val for val in range(1)})
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_calldblstar.py
Python
apache-2.0
383
# test passing a string object as the key for a keyword argument try: exec except NameError: print("SKIP") raise SystemExit # they key in this dict is a string object and is not interned args = {'thisisaverylongargumentname': 123} # when this string is executed it will intern the keyword argument exec("def foo(*,thisisaverylongargumentname=1):\n print(thisisaverylongargumentname)") # test default arg foo() # the string from the dict should match the interned keyword argument foo(**args)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_calldblstar2.py
Python
apache-2.0
509
# test passing a user-defined mapping as the argument to ** def foo(**kw): print(sorted(kw.items())) class Mapping: def keys(self): # the long string checks the case of string interning return ['a', 'b', 'c', 'abcdefghijklmnopqrst'] def __getitem__(self, key): if key == 'a': return 1 else: return 2 foo(**Mapping())
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_calldblstar3.py
Python
apache-2.0
389
# function calls with *pos def foo(a, b, c): print(a, b, c) foo(*(1, 2, 3)) foo(1, *(2, 3)) foo(1, 2, *(3,)) foo(1, 2, 3, *()) # Another sequence type foo(1, 2, *[100]) # Iterator foo(*range(3)) # pos then iterator foo(1, *range(2, 4)) # an iterator with many elements def foo(*rest): print(rest) foo(*range(10)) # method calls with *pos class A: def foo(self, a, b, c): print(a, b, c) a = A() a.foo(*(1, 2, 3)) a.foo(1, *(2, 3)) a.foo(1, 2, *(3,)) a.foo(1, 2, 3, *()) # Another sequence type a.foo(1, 2, *[100]) # Iterator a.foo(*range(3))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_callstar.py
Python
apache-2.0
572
# test calling a function with *tuple and **dict def f(a, b, c, d): print(a, b, c, d) f(*(1, 2), **{'c':3, 'd':4}) f(*(1, 2), **{['c', 'd'][i]:(3 + i) for i in range(2)}) # test calling a method with *tuple and **dict class A: def f(self, a, b, c, d): print(a, b, c, d) a = A() a.f(*(1, 2), **{'c':3, 'd':4}) a.f(*(1, 2), **{['c', 'd'][i]:(3 + i) for i in range(2)})
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_callstardblstar.py
Python
apache-2.0
388
# testing default args to a function def fun1(val=5): print(val) fun1() fun1(10) def fun2(p1, p2=100, p3="foo"): print(p1, p2, p3) fun2(1) fun2(1, None) fun2(0, "bar", 200) try: fun2() except TypeError: print("TypeError") try: fun2(1, 2, 3, 4) except TypeError: print("TypeError") # lambda as default arg (exposes nested behaviour in compiler) def f(x=lambda:1): return x() print(f()) print(f(f)) print(f(lambda:2))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_defargs.py
Python
apache-2.0
449
# overriding default arguments def foo(a, b=3): print(a, b) # override with positional foo(1, 333) # override with keyword foo(1, b=333) # override with keyword foo(a=2, b=333) def foo2(a=1, b=2): print(a, b) # default and keyword foo2(b='two')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_defargs2.py
Python
apache-2.0
259
# test errors from bad function calls # function doesn't take keyword args try: [].append(x=1) except TypeError: print('TypeError') # function with variable number of positional args given too few try: round() except TypeError: print('TypeError') # function with variable number of positional args given too many try: round(1, 2, 3) except TypeError: print('TypeError') # function with fixed number of positional args given wrong number try: [].append(1, 2) except TypeError: print('TypeError') # function with keyword args given extra positional args try: [].sort(1) except TypeError: print('TypeError') # function with keyword args given extra keyword args try: [].sort(noexist=1) except TypeError: print('TypeError') # kw given for positional, but a different positional is missing try: def f(x, y): pass f(x=1) except TypeError: print('TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_error.py
Python
apache-2.0
919
# test errors from bad function calls try: enumerate except: print("SKIP") raise SystemExit # function with keyword args not given a specific keyword arg try: enumerate() except TypeError: print('TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_error2.py
Python
apache-2.0
229
# test the __globals__ attribute of a function def foo(): pass if not hasattr(foo, "__globals__"): print("SKIP") raise SystemExit print(type(foo.__globals__)) print(foo.__globals__ is globals()) foo.__globals__["bar"] = 123 print(bar) try: foo.__globals__ = None except AttributeError: print("AttributeError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_globals.py
Python
apache-2.0
337
def f1(a): print(a) f1(123) f1(a=123) try: f1(b=123) except TypeError: print("TypeError") def f2(a, b): print(a, b) f2(1, 2) f2(a=3, b=4) f2(b=5, a=6) f2(7, b=8) try: f2(9, a=10) except TypeError: print("TypeError") def f3(a, b, *args): print(a, b, args) f3(1, b=3) try: f3(1, a=3) except TypeError: print("TypeError") try: f3(1, 2, 3, 4, a=5) except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_kwargs.py
Python
apache-2.0
431
# to test keyword-only arguments # simplest case def f(*, a): print(a) f(a=1) # with 2 keyword-only args def f(*, a, b): print(a, b) f(a=1, b=2) f(b=1, a=2) # positional followed by bare star def f(a, *, b, c): print(a, b, c) f(1, b=3, c=4) f(1, c=3, b=4) f(1, **{'b':'3', 'c':4}) try: f(1) except TypeError: print("TypeError") try: f(1, b=2) except TypeError: print("TypeError") try: f(1, c=2) except TypeError: print("TypeError") # with **kw def f(a, *, b, **kw): print(a, b, kw) f(1, b=2) f(1, b=2, c=3) # with named star def f(*a, b, c): print(a, b, c) f(b=1, c=2) f(c=1, b=2) # with positional and named star def f(a, *b, c): print(a, b, c) f(1, c=2) f(1, 2, c=3) f(a=1, c=3) # lambda as kw-only arg (exposes nested behaviour in compiler) def f(*, x=lambda:1): return x() print(f()) print(f(x=f)) print(f(x=lambda:2))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_kwonly.py
Python
apache-2.0
891
# test function args, keyword only with default value # a single arg with a default def f1(*, a=1): print(a) f1() f1(a=2) # 1 arg default, 1 not def f2(*, a=1, b): print(a, b) f2(b=2) f2(a=2, b=3) # 1 positional, 1 arg default, 1 not def f3(a, *, b=2, c): print(a, b, c) f3(1, c=3) f3(1, b=3, c=4) f3(1, **{'c':3}) f3(1, **{'b':'3', 'c':4}) # many args, not all with defaults def f4(*, a=1, b, c=3, d, e=5, f): print(a, b, c, d, e, f) f4(b=2, d=4, f=6) f4(a=11, b=2, d=4, f=6) f4(a=11, b=2, c=33, d=4, e=55, f=6) f4(f=6, e=55, d=4, c=33, b=2, a=11) # positional with default, then keyword only def f5(a, b=4, *c, d=8): print(a, b, c, d) f5(1) f5(1, d=9) f5(1, b=44, d=9)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_kwonlydef.py
Python
apache-2.0
696
def f1(**kwargs): print(kwargs) f1() f1(a=1) def f2(a, **kwargs): print(a, kwargs) f2(1) f2(1, b=2) def f3(a, *vargs, **kwargs): print(a, vargs, kwargs) f3(1) f3(1, 2) f3(1, b=2) f3(1, 2, b=3) def f4(*vargs, **kwargs): print(vargs, kwargs) f4(*(1, 2)) f4(kw_arg=3) f4(*(1, 2), kw_arg=3)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_kwvarargs.py
Python
apache-2.0
309
# test large function (stack) state # this function creates 127 locals def f(): x0 = 1 x1 = 1 x2 = 1 x3 = 1 x4 = 1 x5 = 1 x6 = 1 x7 = 1 x8 = 1 x9 = 1 x10 = 1 x11 = 1 x12 = 1 x13 = 1 x14 = 1 x15 = 1 x16 = 1 x17 = 1 x18 = 1 x19 = 1 x20 = 1 x21 = 1 x22 = 1 x23 = 1 x24 = 1 x25 = 1 x26 = 1 x27 = 1 x28 = 1 x29 = 1 x30 = 1 x31 = 1 x32 = 1 x33 = 1 x34 = 1 x35 = 1 x36 = 1 x37 = 1 x38 = 1 x39 = 1 x40 = 1 x41 = 1 x42 = 1 x43 = 1 x44 = 1 x45 = 1 x46 = 1 x47 = 1 x48 = 1 x49 = 1 x50 = 1 x51 = 1 x52 = 1 x53 = 1 x54 = 1 x55 = 1 x56 = 1 x57 = 1 x58 = 1 x59 = 1 x60 = 1 x61 = 1 x62 = 1 x63 = 1 x64 = 1 x65 = 1 x66 = 1 x67 = 1 x68 = 1 x69 = 1 x70 = 1 x71 = 1 x72 = 1 x73 = 1 x74 = 1 x75 = 1 x76 = 1 x77 = 1 x78 = 1 x79 = 1 x80 = 1 x81 = 1 x82 = 1 x83 = 1 x84 = 1 x85 = 1 x86 = 1 x87 = 1 x88 = 1 x89 = 1 x90 = 1 x91 = 1 x92 = 1 x93 = 1 x94 = 1 x95 = 1 x96 = 1 x97 = 1 x98 = 1 x99 = 1 x100 = 1 x101 = 1 x102 = 1 x103 = 1 x104 = 1 x105 = 1 x106 = 1 x107 = 1 x108 = 1 x109 = 1 x110 = 1 x111 = 1 x112 = 1 x113 = 1 x114 = 1 x115 = 1 x116 = 1 x117 = 1 x118 = 1 x119 = 1 x120 = 1 x121 = 1 x122 = 1 x123 = 1 x124 = 1 x125 = 1 x126 = 1 f() # this function pushes 128 elements onto the function stack def g(): x = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,] g() # this function exercises load_fast_n and store_fast_n opcodes def h(): x0 = 1 x1 = x0 x2 = x1 x3 = x2 x4 = x3 x5 = x4 x6 = x5 x7 = x6 x8 = x7 x9 = x8 x10 = x9 x11 = x10 x12 = x11 x13 = x12 x14 = x13 x15 = x14 x16 = x15 x17 = x16 h()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_largestate.py
Python
apache-2.0
2,401
def Fun(): pass class A: def __init__(self): pass def Fun(self): pass try: print(Fun.__name__) print(A.__init__.__name__) print(A.Fun.__name__) print(A().Fun.__name__) except AttributeError: print('SKIP') raise SystemExit # __name__ of a bound native method is not implemented in uPy # the test here is to make sure it doesn't crash try: str((1).to_bytes.__name__) except AttributeError: pass # name of a function that has closed over variables def outer(): x = 1 def inner(): return x return inner print(outer.__name__)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_name.py
Python
apache-2.0
605
# test str of function def f(): pass print(str(f)[:8])
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_str.py
Python
apache-2.0
60
# function with just varargs def f1(*args): print(args) f1() f1(1) f1(1, 2) # function with 1 arg, then varargs def f2(a, *args): print(a, args) f2(1) f2(1, 2) f2(1, 2, 3) # function with 2 args, then varargs def f3(a, b, *args): print(a, b, args) f3(1, 2) f3(1, 2, 3) f3(1, 2, 3, 4) # function with 1 default arg, then varargs def f4(a=0, *args): print(a, args) f4() f4(1) f4(1, 2) f4(1, 2, 3) # function with 1 arg, 1 default arg, then varargs def f5(a, b=0, *args): print(a, b, args) f5(1) f5(1, 2) f5(1, 2, 3) f5(1, 2, 3, 4)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/fun_varargs.py
Python
apache-2.0
558
# basic tests for gc module try: import gc except ImportError: print("SKIP") raise SystemExit print(gc.isenabled()) gc.disable() print(gc.isenabled()) gc.enable() print(gc.isenabled()) gc.collect() if hasattr(gc, 'mem_free'): # uPy has these extra functions # just test they execute and return an int assert type(gc.mem_free()) is int assert type(gc.mem_alloc()) is int if hasattr(gc, 'threshold'): # uPy has this extra function # check execution and returns assert(gc.threshold(1) is None) assert(gc.threshold() == 0) assert(gc.threshold(-1) is None) assert(gc.threshold() == -1) # Setting a low threshold should trigger collection at the list alloc gc.threshold(1) [[], []] gc.threshold(-1)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gc1.py
Python
apache-2.0
767
# Case of terminating subgen using return with value def gen(): yield 1 yield 2 return 3 def gen2(): print("here1") print((yield from gen())) print("here2") g = gen2() print(list(g)) # StopIteration from within a Python function, within a native iterator (map), within a yield from def gen7(x): if x < 3: return x else: raise StopIteration(444) def gen8(): print((yield from map(gen7, range(100)))) g = gen8() print(list(g))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from.py
Python
apache-2.0
483
def gen(): yield 1 yield 2 yield 3 yield 4 def gen2(): yield -1 print((yield from gen())) yield 10 yield 11 g = gen2() print(next(g)) print(next(g)) g.close() try: print(next(g)) except StopIteration: print("StopIteration") # Now variation of same test, but with leaf generator # swallowing GeneratorExit exception - its upstream gen # generator should still receive one. def gen3(): yield 1 try: yield 2 except GeneratorExit: print("leaf caught GeneratorExit and swallowed it") return yield 3 yield 4 def gen4(): yield -1 try: print((yield from gen3())) except GeneratorExit: print("delegating caught GeneratorExit") raise yield 10 yield 11 g = gen4() print(next(g)) print(next(g)) print(next(g)) g.close() try: print(next(g)) except StopIteration: print("StopIteration") # Yet another variation - leaf generator gets GeneratorExit, # and reraises a new GeneratorExit. This still should close chain properly. def gen5(): yield 1 try: yield 2 except GeneratorExit: print("leaf caught GeneratorExit and reraised GeneratorExit") raise GeneratorExit(123) yield 3 yield 4 def gen6(): yield -1 try: print((yield from gen5())) except GeneratorExit: print("delegating caught GeneratorExit") raise yield 10 yield 11 g = gen6() print(next(g)) print(next(g)) print(next(g)) g.close() try: print(next(g)) except StopIteration: print("StopIteration") # case where generator ignores the close request and yields instead def gen7(): try: yield 123 except GeneratorExit: yield 456 g = gen7() print(next(g)) try: g.close() except RuntimeError: print('RuntimeError') # case where close is propagated up to a built-in iterator def gen8(): g = range(2) yield from g g = gen8() print(next(g)) g.close() # case with a user-defined close method class Iter: def __iter__(self): return self def __next__(self): return 1 def close(self): print('close') def gen9(): yield from Iter() g = gen9() print(next(g)) g.close()
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_close.py
Python
apache-2.0
2,220
class MyGen: def __init__(self): self.v = 0 def __iter__(self): return self def __next__(self): self.v += 1 if self.v > 5: raise StopIteration return self.v def gen(): yield from MyGen() def gen2(): yield from gen() print(list(gen())) print(list(gen2())) class Incrementer: def __iter__(self): return self def __next__(self): return self.send(None) def send(self, val): if val is None: return "Incrementer initialized" return val + 1 def gen3(): yield from Incrementer() g = gen3() print(next(g)) print(g.send(5)) print(g.send(100)) # # Test proper handling of StopIteration vs other exceptions # class MyIter: def __iter__(self): return self def __next__(self): raise StopIteration(42) def gen4(): global ret ret = yield from MyIter() 1//0 ret = None try: print(list(gen4())) except ZeroDivisionError: print("ZeroDivisionError") print(ret)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_ducktype.py
Python
apache-2.0
1,034
def gen(): yield 1 yield 2 raise ValueError def gen2(): try: print((yield from gen())) except ValueError: print("caught ValueError from downstream") g = gen2() print(list(g))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_exc.py
Python
apache-2.0
213
# yielding from an already executing generator is not allowed def f(): yield 1 # g here is already executing so this will raise an exception yield from g g = f() print(next(g)) try: next(g) except ValueError: print('ValueError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_executing.py
Python
apache-2.0
253
def gen(): yield from (1, 2, 3) def gen2(): yield from gen() def gen3(): yield from (4, 5) yield 6 print(list(gen())) print(list(gen2())) print(list(gen3()))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_iter.py
Python
apache-2.0
177
# Tests that the pending exception state is managed correctly # (previously failed on native emitter). def noop_task(): print('noop task') yield 1 def raise_task(): print('raise task') yield 2 print('raising') raise Exception def main(): try: yield from raise_task() except: print('main exception') yield from noop_task() for z in main(): print('outer iter', z)
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_pending.py
Python
apache-2.0
423
def gen(): print("sent:", (yield 1)) yield 2 def gen2(): print((yield from gen())) g = gen2() next(g) print("yielded:", g.send("val")) try: next(g) except StopIteration: print("StopIteration")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_send.py
Python
apache-2.0
215
# Yielding from stopped generator is ok and results in None def gen(): return 1 # This yield is just to make this a generator yield f = gen() def run(): print((yield from f)) print((yield from f)) print((yield from f)) try: next(run()) except StopIteration: print("StopIteration") # Where "f" is a native generator def run(): print((yield from f)) f = zip() try: next(run()) except StopIteration: print("StopIteration")
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_stopped.py
Python
apache-2.0
472
def gen(): try: yield 1 except ValueError as e: print("got ValueError from upstream!", repr(e.args)) yield "str1" raise TypeError def gen2(): print((yield from gen())) g = gen2() print(next(g)) print(g.throw(ValueError)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing None as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, None)) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # passing an exception instance as second argument to throw g = gen2() print(next(g)) print(g.throw(ValueError, ValueError(123))) try: print(next(g)) except TypeError: print("got TypeError from downstream!") # thrown value is caught and then generator returns normally def gen(): try: yield 123 except ValueError: print('ValueError') # return normally after catching thrown exception def gen2(): yield from gen() yield 789 g = gen2() print(next(g)) print(g.throw(ValueError))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_throw.py
Python
apache-2.0
1,056
# outer generator ignores a thrown GeneratorExit (this is allowed) def gen(): try: yield 123 except GeneratorExit: print('GeneratorExit') def gen2(): try: yield from gen() except GeneratorExit: print('GeneratorExit outer') yield 789 # thrown a class g = gen2() print(next(g)) print(g.throw(GeneratorExit)) # thrown an instance g = gen2() print(next(g)) print(g.throw(GeneratorExit()))
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_throw2.py
Python
apache-2.0
441
# yield-from a user-defined generator with a throw() method class Iter: def __iter__(self): return self def __next__(self): return 1 def throw(self, x): print('throw', x) return 456 def gen(): yield from Iter() # calling close() should not call throw() g = gen() print(next(g)) g.close() # can throw a non-exception object g = gen() print(next(g)) print(g.throw(123)) # throwing an exception class just injects that class g = gen() print(next(g)) print(g.throw(ZeroDivisionError)) # this user-defined generator doesn't have a throw() method class Iter2: def __iter__(self): return self def __next__(self): return 1 def gen2(): yield from Iter2() # the thrown ValueError is not intercepted by the user class g = gen2() print(next(g)) try: g.throw(ValueError) except: print('ValueError') # the thrown 123 is not an exception so raises a TypeError g = gen2() print(next(g)) try: g.throw(123) except TypeError: print('TypeError')
YifuLiu/AliOS-Things
components/py_engine/tests/basics/gen_yield_from_throw3.py
Python
apache-2.0
1,030
def f(x): print('a') y = x print('b') while y > 0: print('c') y -= 1 print('d') yield y print('e') print('f') return None for val in f(3): print(val) #gen = f(3) #print(gen) #print(gen.__next__()) #print(gen.__next__()) #print(gen.__next__()) #print(gen.__next__()) # test printing, but only the first chars that match CPython print(repr(f(0))[0:17])
YifuLiu/AliOS-Things
components/py_engine/tests/basics/generator1.py
Python
apache-2.0
422