├── .gitignore ├── design1 └── cs173-python │ ├── get-structured-python.rkt │ ├── list.py │ ├── parse-python.rkt │ ├── py-prelude.py │ ├── python-core-syntax.rkt │ ├── python-desugar.rkt │ ├── python-evaluator.rkt │ ├── python-interp-helpers.rkt │ ├── python-interp.rkt │ ├── python-lib.rkt │ ├── python-main.rkt │ ├── python-objects.rkt │ ├── python-parser.py │ ├── python-primitives.rkt │ ├── python-syntax.rkt │ ├── python_eval.sublime-project │ ├── python_eval.sublime-workspace │ ├── report.txt │ ├── run-tests.rkt │ ├── scope_tests.sublime-project │ ├── scope_tests.sublime-workspace │ ├── sim.py │ ├── test.py │ ├── tojson.sh │ ├── type_tests.sublime-project │ └── type_tests.sublime-workspace ├── design2 └── python │ ├── .gitignore │ ├── LIST_OF_UNDERBARS │ ├── basic.rkt │ ├── get-structured-python.rkt │ ├── interp.sh │ ├── james-tests │ ├── assertfalse.py │ ├── asserttrue.py │ ├── def-noargs.py │ ├── def.py │ ├── emptyfun.py │ ├── global-first-assign-in-func.py │ ├── if.py │ ├── no-binding-for-nonlocal.py │ ├── unbound-explicit-global.py │ ├── unbound-implicit-global.py │ └── unboundlocal.py │ ├── parse-python.rkt │ ├── py-prelude.py │ ├── python-core-syntax.rkt │ ├── python-desugar.rkt │ ├── python-evaluator.rkt │ ├── python-interp.rkt │ ├── python-lib.rkt │ ├── python-main.rkt │ ├── python-parser.py │ ├── python-primitives.rkt │ ├── python-reference │ ├── bool │ │ ├── bool-callable.py │ │ ├── bool-compare-list-dict.py │ │ ├── bool-compare.py │ │ ├── bool-convert.py │ │ ├── bool-float.py │ │ ├── bool-int.py │ │ ├── bool-isinstance.py │ │ ├── bool-math.py │ │ └── bool-str.py │ ├── builtin │ │ ├── all.py │ │ ├── any.py │ │ ├── callable.py │ │ ├── filter.py │ │ ├── isinstance.py │ │ └── len.py │ ├── dict │ │ ├── dict-bool.py │ │ ├── dict-clear.py │ │ ├── dict-contains.py │ │ ├── dict-get.py │ │ ├── dict-getitem.py │ │ ├── dict-items.py │ │ ├── dict-keys.py │ │ ├── dict-set-keys.py │ │ ├── dict-update.py │ │ ├── dict-values-set.py │ │ └── dict-values.py │ ├── exceptions │ │ ├── except-reraise.py │ │ ├── invalid-reraise.py │ │ ├── nested-else.py │ │ ├── nested-reraise.py │ │ ├── nested.py │ │ ├── reraise.py │ │ ├── test-finally-reraise.py │ │ ├── test-try-except-else.py │ │ ├── test-try-except-no-exception.py │ │ ├── test-try-except.py │ │ ├── try-except-else-finally-no-exception.py │ │ ├── try-except-else-finally.py │ │ ├── try-except-else-no-exception.py │ │ ├── try-except-finally-no-exception.py │ │ ├── try-except-finally.py │ │ └── try-finally-no-exception.py │ ├── iter │ │ ├── iter-classes.py │ │ ├── iter-comprehensions.py │ │ ├── iter-misc.py │ │ ├── iter-simple.py │ │ └── iter-stop.py │ ├── lists │ │ ├── test_list_identity.py │ │ ├── test_list_simple.py │ │ └── test_list_truth.py │ ├── range │ │ ├── range-errs.py │ │ ├── range-list.py │ │ └── range-vars.py │ ├── scope │ │ ├── bound-and-free.py │ │ ├── extra-nesting.py │ │ ├── freevar-in-method.py │ │ ├── lambda1.py │ │ ├── lambda2.py │ │ ├── lambda3.py │ │ ├── lambda4.py │ │ ├── locals-class.py │ │ ├── locals-function.py │ │ ├── mixed-freevars-and-cellvars.py │ │ ├── nearest-enclosing-scope.py │ │ ├── nested-nonlocal.py │ │ ├── nesting-global-no-free.py │ │ ├── nesting-plus-free-ref-to-global.py │ │ ├── nesting-through-class.py │ │ ├── nonlocal-class.py │ │ ├── nonlocal-function.py │ │ ├── nonlocal-method.py │ │ ├── recursion.py │ │ ├── simple-and-rebinding.py │ │ ├── simple-nesting.py │ │ └── unbound-local.py │ ├── super │ │ └── test-super.py │ ├── tuple │ │ ├── tuple-add.py │ │ ├── tuple-constructors.py │ │ ├── tuple-length.py │ │ ├── tuple-mul.py │ │ └── tuple-truth.py │ └── types │ │ ├── test_booleans.py │ │ ├── test_comparisons.py │ │ ├── test_div_zero.py │ │ ├── test_floats.py │ │ ├── test_simple_string_ops.py │ │ ├── test_simple_strings.py │ │ ├── test_string_slices.py │ │ ├── types_truthy1.py │ │ └── types_truthy2.py │ ├── python-syntax.rkt │ ├── run-tests.rkt │ ├── run.sh │ ├── test.py │ ├── test.sh │ └── test2.py ├── design3 └── cs173-python │ ├── .gitignore │ ├── get-structured-python.rkt │ ├── parse-python.rkt │ ├── py-prelude.py │ ├── python-core-syntax.rkt │ ├── python-desugar.rkt │ ├── python-evaluator.rkt │ ├── python-examples │ ├── basic.py │ ├── funcs.py │ ├── if-then-else.py │ ├── if-then.py │ ├── nonlocal.py │ └── varargs.py │ ├── python-interp.rkt │ ├── python-lib.rkt │ ├── python-main.rkt │ ├── python-monad.rkt │ ├── python-parser.py │ ├── python-reference │ ├── bool │ │ ├── bool-callable.py │ │ ├── bool-compare-list-dict.py │ │ ├── bool-compare.py │ │ ├── bool-convert.py │ │ ├── bool-float.py │ │ ├── bool-int.py │ │ ├── bool-isinstance.py │ │ ├── bool-math.py │ │ └── bool-str.py │ ├── builtin │ │ ├── all.py │ │ ├── any.py │ │ ├── callable.py │ │ ├── filter.py │ │ ├── isinstance.py │ │ └── len.py │ ├── dict │ │ ├── dict-bool.py │ │ ├── dict-clear.py │ │ ├── dict-contains.py │ │ ├── dict-get.py │ │ ├── dict-getitem.py │ │ ├── dict-items.py │ │ ├── dict-keys.py │ │ ├── dict-set-keys.py │ │ ├── dict-update.py │ │ ├── dict-values-set.py │ │ └── dict-values.py │ ├── exceptions │ │ ├── except-reraise.py │ │ ├── invalid-reraise.py │ │ ├── nested-else.py │ │ ├── nested-reraise.py │ │ ├── nested.py │ │ ├── reraise.py │ │ ├── test-finally-reraise.py │ │ ├── test-try-except-else.py │ │ ├── test-try-except-no-exception.py │ │ ├── test-try-except.py │ │ ├── try-except-else-finally-no-exception.py │ │ ├── try-except-else-finally.py │ │ ├── try-except-else-no-exception.py │ │ ├── try-except-finally-no-exception.py │ │ ├── try-except-finally.py │ │ └── try-finally-no-exception.py │ ├── iter │ │ ├── iter-classes.py │ │ ├── iter-comprehensions.py │ │ ├── iter-misc.py │ │ ├── iter-simple.py │ │ └── iter-stop.py │ ├── lists │ │ ├── test_list_identity.py │ │ ├── test_list_simple.py │ │ └── test_list_truth.py │ ├── range │ │ ├── range-errs.py │ │ ├── range-list.py │ │ └── range-vars.py │ ├── scope │ │ ├── bound-and-free.py │ │ ├── extra-nesting.py │ │ ├── freevar-in-method.py │ │ ├── lambda1.py │ │ ├── lambda2.py │ │ ├── lambda3.py │ │ ├── lambda4.py │ │ ├── locals-class.py │ │ ├── locals-function.py │ │ ├── mixed-freevars-and-cellvars.py │ │ ├── nearest-enclosing-scope.py │ │ ├── nested-nonlocal.py │ │ ├── nesting-global-no-free.py │ │ ├── nesting-plus-free-ref-to-global.py │ │ ├── nesting-through-class.py │ │ ├── nonlocal-class.py │ │ ├── nonlocal-function.py │ │ ├── nonlocal-method.py │ │ ├── recursion.py │ │ ├── simple-and-rebinding.py │ │ ├── simple-nesting.py │ │ └── unbound-local.py │ ├── super │ │ └── test-super.py │ ├── tuple │ │ ├── tuple-add.py │ │ ├── tuple-constructors.py │ │ ├── tuple-length.py │ │ ├── tuple-mul.py │ │ └── tuple-truth.py │ └── types │ │ ├── test_booleans.py │ │ ├── test_comparisons.py │ │ ├── test_div_zero.py │ │ ├── test_floats.py │ │ ├── test_simple_string_ops.py │ │ ├── test_simple_strings.py │ │ ├── test_string_slices.py │ │ ├── types_truthy1.py │ │ └── types_truthy2.py │ ├── python-syntax.rkt │ └── run-tests.rkt ├── design4 └── cs173-python │ ├── .gitignore │ ├── LANGUAGES.txt │ ├── README.txt │ ├── get-structured-python.rkt │ ├── parse-python.rkt │ ├── py-prelude.py │ ├── python-core-syntax.rkt │ ├── python-cps.rkt │ ├── python-desugar-core.rkt │ ├── python-desugar.rkt │ ├── python-evaluator.rkt │ ├── python-helpers.rkt │ ├── python-interp.rkt │ ├── python-lib.rkt │ ├── python-main.rkt │ ├── python-micro-syntax.rkt │ ├── python-parser.py │ ├── python-primitives.rkt │ ├── python-reference │ ├── bool │ │ ├── bool-callable.py │ │ ├── bool-compare-list-dict.py │ │ ├── bool-compare.py │ │ ├── bool-convert.py │ │ ├── bool-float.py │ │ ├── bool-int.py │ │ ├── bool-isinstance.py │ │ ├── bool-math.py │ │ └── bool-str.py │ ├── builtin │ │ ├── all.py │ │ ├── any.py │ │ ├── callable.py │ │ ├── filter.py │ │ ├── isinstance.py │ │ └── len.py │ ├── dict │ │ ├── dict-bool.py │ │ ├── dict-clear.py │ │ ├── dict-contains.py │ │ ├── dict-get.py │ │ ├── dict-getitem.py │ │ ├── dict-items.py │ │ ├── dict-keys.py │ │ ├── dict-set-keys.py │ │ ├── dict-update.py │ │ ├── dict-values-set.py │ │ └── dict-values.py │ ├── exceptions │ │ ├── except-reraise.py │ │ ├── invalid-reraise.py │ │ ├── nested-else.py │ │ ├── nested-reraise.py │ │ ├── nested.py │ │ ├── reraise.py │ │ ├── test-finally-reraise.py │ │ ├── test-try-except-else.py │ │ ├── test-try-except-no-exception.py │ │ ├── test-try-except.py │ │ ├── try-except-else-finally-no-exception.py │ │ ├── try-except-else-finally.py │ │ ├── try-except-else-no-exception.py │ │ ├── try-except-finally-no-exception.py │ │ ├── try-except-finally.py │ │ └── try-finally-no-exception.py │ ├── iter │ │ ├── iter-classes.py │ │ ├── iter-comprehensions.py │ │ ├── iter-misc.py │ │ ├── iter-simple.py │ │ └── iter-stop.py │ ├── lists │ │ ├── test_list_identity.py │ │ ├── test_list_simple.py │ │ └── test_list_truth.py │ ├── range │ │ ├── range-errs.py │ │ ├── range-list.py │ │ └── range-vars.py │ ├── scope │ │ ├── bound-and-free.py │ │ ├── extra-nesting.py │ │ ├── freevar-in-method.py │ │ ├── lambda1.py │ │ ├── lambda2.py │ │ ├── lambda3.py │ │ ├── lambda4.py │ │ ├── locals-class.py │ │ ├── locals-function.py │ │ ├── mixed-freevars-and-cellvars.py │ │ ├── nearest-enclosing-scope.py │ │ ├── nested-nonlocal.py │ │ ├── nesting-global-no-free.py │ │ ├── nesting-plus-free-ref-to-global.py │ │ ├── nesting-through-class.py │ │ ├── nonlocal-class.py │ │ ├── nonlocal-function.py │ │ ├── nonlocal-method.py │ │ ├── recursion.py │ │ ├── simple-and-rebinding.py │ │ ├── simple-nesting.py │ │ └── unbound-local.py │ ├── super │ │ └── test-super.py │ ├── tuple │ │ ├── tuple-add.py │ │ ├── tuple-constructors.py │ │ ├── tuple-length.py │ │ ├── tuple-mul.py │ │ └── tuple-truth.py │ └── types │ │ ├── test_booleans.py │ │ ├── test_comparisons.py │ │ ├── test_div_zero.py │ │ ├── test_floats.py │ │ ├── test_simple_string_ops.py │ │ ├── test_simple_strings.py │ │ ├── test_string_slices.py │ │ ├── types_truthy1.py │ │ └── types_truthy2.py │ ├── python-syntax.rkt │ ├── python-tests.rkt │ └── run-tests.rkt ├── design5 ├── README ├── get-structured-python.rkt ├── parse-python.rkt ├── python-core-syntax.rkt ├── python-desugar.rkt ├── python-evaluator.rkt ├── python-interp.rkt ├── python-lib.rkt ├── python-main.rkt ├── python-parser.py ├── python-primitives.rkt ├── python-syntax.rkt └── run-tests.rkt ├── get-structured-python.rkt ├── parse-python.rkt ├── py-prelude.py ├── python-core-syntax.rkt ├── python-desugar.rkt ├── python-evaluator.rkt ├── python-interp.rkt ├── python-lib.rkt ├── python-main.rkt ├── python-parser.py ├── python-primitives.rkt ├── python-reference ├── bool │ ├── bool-callable.py │ ├── bool-compare-list-dict.py │ ├── bool-compare.py │ ├── bool-convert.py │ ├── bool-float.py │ ├── bool-int.py │ ├── bool-isinstance.py │ ├── bool-math.py │ └── bool-str.py ├── builtin │ ├── all.py │ ├── any.py │ ├── callable.py │ ├── filter.py │ ├── isinstance.py │ └── len.py ├── dict │ ├── dict-bool.py │ ├── dict-clear.py │ ├── dict-contains.py │ ├── dict-get.py │ ├── dict-getitem.py │ ├── dict-items.py │ ├── dict-keys.py │ ├── dict-set-keys.py │ ├── dict-update.py │ ├── dict-values-set.py │ └── dict-values.py ├── exceptions │ ├── except-reraise.py │ ├── invalid-reraise.py │ ├── nested-else.py │ ├── nested-reraise.py │ ├── nested.py │ ├── reraise.py │ ├── test-finally-reraise.py │ ├── test-try-except-else.py │ ├── test-try-except-no-exception.py │ ├── test-try-except.py │ ├── try-except-else-finally-no-exception.py │ ├── try-except-else-finally.py │ ├── try-except-else-no-exception.py │ ├── try-except-finally-no-exception.py │ ├── try-except-finally.py │ └── try-finally-no-exception.py ├── iter │ ├── iter-classes.py │ ├── iter-comprehensions.py │ ├── iter-misc.py │ ├── iter-simple.py │ └── iter-stop.py ├── lists │ ├── test_list_identity.py │ ├── test_list_simple.py │ └── test_list_truth.py ├── range │ ├── range-errs.py │ ├── range-list.py │ └── range-vars.py ├── scope │ ├── bound-and-free.py │ ├── extra-nesting.py │ ├── freevar-in-method.py │ ├── lambda1.py │ ├── lambda2.py │ ├── lambda3.py │ ├── lambda4.py │ ├── locals-class.py │ ├── locals-function.py │ ├── mixed-freevars-and-cellvars.py │ ├── nearest-enclosing-scope.py │ ├── nested-nonlocal.py │ ├── nesting-global-no-free.py │ ├── nesting-plus-free-ref-to-global.py │ ├── nesting-through-class.py │ ├── nonlocal-class.py │ ├── nonlocal-function.py │ ├── nonlocal-method.py │ ├── recursion.py │ ├── simple-and-rebinding.py │ ├── simple-nesting.py │ └── unbound-local.py ├── super │ └── test-super.py ├── tuple │ ├── tuple-add.py │ ├── tuple-constructors.py │ ├── tuple-length.py │ ├── tuple-mul.py │ └── tuple-truth.py └── types │ ├── test_booleans.py │ ├── test_comparisons.py │ ├── test_div_zero.py │ ├── test_floats.py │ ├── test_simple_string_ops.py │ ├── test_simple_strings.py │ ├── test_string_slices.py │ ├── types_truthy1.py │ └── types_truthy2.py ├── python-syntax.rkt └── run-tests.rkt /.gitignore: -------------------------------------------------------------------------------- 1 | compiled/ 2 | *.swp 3 | *~ 4 | -------------------------------------------------------------------------------- /design1/cs173-python/list.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3] 2 | print(a) 3 | -------------------------------------------------------------------------------- /design1/cs173-python/parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /design1/cs173-python/py-prelude.py: -------------------------------------------------------------------------------- 1 | def ___assertEqual(l, r): 2 | assert(l == r) 3 | 4 | def ___assertNotEqual(l, r): 5 | assert(not (l == r)) 6 | 7 | def ___assertTrue(v): 8 | assert(v) 9 | 10 | def ___assertFalse(v): 11 | assert(not v) 12 | 13 | def ___assertIs(l, r): 14 | assert(l is r) 15 | 16 | def ___assertIsNot(l, r): 17 | assert(not (l is r)) 18 | 19 | def ___assertIn(l, r): 20 | assert(l in r) 21 | 22 | def ___assertNotIn(l, r): 23 | assert(not (l in r)) 24 | 25 | def ___assertRaises(e, f, *args): 26 | try: 27 | f(*args) 28 | except e as the_exn: 29 | return 30 | else: 31 | assert(False) 32 | assert(False) 33 | 34 | def ___fail(): 35 | assert(False) 36 | -------------------------------------------------------------------------------- /design1/cs173-python/python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | else: 22 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 23 | % v) 24 | 25 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 26 | n_dict['nodetype'] = n.__class__.__name__ 27 | return n_dict 28 | 29 | if __name__ == '__main__': 30 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 31 | -------------------------------------------------------------------------------- /design1/cs173-python/python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (define-type PyExpr 4 | [PySeq (es : (listof PyExpr))] 5 | 6 | ;;represents primitive operation with two or more arguments 7 | [PyBoolOp (op : symbol) (values : (listof PyExpr))] 8 | 9 | [PyBinOp (op : symbol) (left : PyExpr) (right : PyExpr)] 10 | 11 | ;;represents unary primitives 12 | [PyPrimOp (op : symbol) (arg : PyExpr)] 13 | 14 | ;;represents if statement 15 | [PyIf (test : PyExpr) (body : PyExpr) (orelse : PyExpr)] 16 | 17 | [PyComp (left : PyExpr) (ops : (listof symbol)) (comparators : (listof PyExpr))] 18 | 19 | [PyAssign (lhs : PyExpr) (value : PyExpr)] 20 | 21 | [PyLambda (args : (listof symbol)) (body : PyExpr)] 22 | 23 | [PyVoid] 24 | [PyPass] 25 | 26 | [PyRaise (exn : PyExpr)] 27 | 28 | [PyNum (n : number)] 29 | [PyStr (s : string)] 30 | [PyList (mutable : boolean) (elts : (listof PyExpr))] 31 | [PyId (x : symbol)] 32 | [PyApp (fun : PyExpr) (args : (listof PyExpr))]) 33 | 34 | -------------------------------------------------------------------------------- /design1/cs173-python/python_eval.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | } 3 | -------------------------------------------------------------------------------- /design1/cs173-python/scope_tests.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | } 3 | -------------------------------------------------------------------------------- /design1/cs173-python/sim.py: -------------------------------------------------------------------------------- 1 | print(5+3) 2 | -------------------------------------------------------------------------------- /design1/cs173-python/test.py: -------------------------------------------------------------------------------- 1 | print(5) 2 | print(True) 3 | print(True and False) 4 | print("a") 5 | print('a') 6 | print(9 + 9) 7 | print(9 < 9) 8 | -------------------------------------------------------------------------------- /design1/cs173-python/tojson.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cat $1 | /course/cs173/python/Python-3.2.3/python python-parser.py | /course/cs173/python/Python-3.2.3/python bin/jsbeautifier.py -i 4 | -------------------------------------------------------------------------------- /design1/cs173-python/type_tests.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | } 3 | -------------------------------------------------------------------------------- /design2/python/.gitignore: -------------------------------------------------------------------------------- 1 | compiled/ 2 | *.swp 3 | *~ 4 | *.bak 5 | *.1 6 | -------------------------------------------------------------------------------- /design2/python/LIST_OF_UNDERBARS: -------------------------------------------------------------------------------- 1 | ./python-reference/dict/dict-getitem.py:___assertRaises(TypeError, d.__getitem__) 2 | ./python-reference/iter/iter-classes.py: def __init__(self, n): 3 | ./python-reference/iter/iter-classes.py: def __next__(self): 4 | ./python-reference/iter/iter-classes.py: def __init__(self, n): 5 | ./python-reference/iter/iter-classes.py: def __iter__(self): 6 | ./python-reference/iter/iter-classes.py: def __init__(self, n): 7 | ./python-reference/iter/iter-classes.py: def __getitem__(self, i): 8 | ./python-reference/scope/nesting-through-class.py: def __call__(self, y): 9 | ./python-reference/scope/nonlocal-class.py:___assertNotIn("x", c.__class__.__dict__) 10 | -------------------------------------------------------------------------------- /design2/python/basic.rkt: -------------------------------------------------------------------------------- 1 | #lang plai 2 | 3 | (require racket/match 4 | racket/list) 5 | 6 | (define (pretty-struct s) 7 | (pretty-write s)) 8 | 9 | (define (pretty-store s) 10 | (pretty-write s)) 11 | 12 | (define (pretty-scopedb s) 13 | (pretty-write s)) -------------------------------------------------------------------------------- /design2/python/interp.sh: -------------------------------------------------------------------------------- 1 | ./run.sh --interp 2 | -------------------------------------------------------------------------------- /design2/python/james-tests/assertfalse.py: -------------------------------------------------------------------------------- 1 | ___assertFalse(False) 2 | -------------------------------------------------------------------------------- /design2/python/james-tests/asserttrue.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(True) 2 | 3 | -------------------------------------------------------------------------------- /design2/python/james-tests/def-noargs.py: -------------------------------------------------------------------------------- 1 | def noargs(): 2 | print("noargs success!") 3 | 4 | noargs() 5 | noargs() 6 | 7 | -------------------------------------------------------------------------------- /design2/python/james-tests/def.py: -------------------------------------------------------------------------------- 1 | def noargs(): 2 | print("noargs") 3 | 4 | def onearg(x): 5 | print(x) 6 | 7 | def twoargs(x,y): 8 | print(x) 9 | print(y) 10 | 11 | noargs() 12 | onearg("onearg") 13 | twoargs("two", "args") 14 | -------------------------------------------------------------------------------- /design2/python/james-tests/emptyfun.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | pass 3 | 4 | print("calling foo..."); 5 | foo() 6 | print("done"); 7 | -------------------------------------------------------------------------------- /design2/python/james-tests/global-first-assign-in-func.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | global x 3 | x = 3 4 | 5 | foo() 6 | 7 | print(x) 8 | -------------------------------------------------------------------------------- /design2/python/james-tests/if.py: -------------------------------------------------------------------------------- 1 | if True: 2 | print("if1-true") 3 | elif True: 4 | print("if1-elif") 5 | else: 6 | print("if1-else") 7 | 8 | if False: 9 | print("if2-true") 10 | elif True: 11 | print("if2-elif") 12 | else: 13 | print("if2-else") 14 | 15 | if False: 16 | print("if3-true") 17 | elif False: 18 | print("if3-elif") 19 | else: 20 | print("if3-else") 21 | -------------------------------------------------------------------------------- /design2/python/james-tests/no-binding-for-nonlocal.py: -------------------------------------------------------------------------------- 1 | # should produce: SyntaxError: no binding for nonlocal 'a' found 2 | # at time of function definition 3 | 4 | def foo(foo_arg): 5 | def bar(bar_arg): 6 | nonlocal a 7 | 8 | #foo(0); 9 | 10 | print("should not get here") 11 | -------------------------------------------------------------------------------- /design2/python/james-tests/unbound-explicit-global.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | global x 3 | print(x) 4 | 5 | foo() 6 | 7 | -------------------------------------------------------------------------------- /design2/python/james-tests/unbound-implicit-global.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | print(x) 3 | 4 | foo() 5 | 6 | -------------------------------------------------------------------------------- /design2/python/james-tests/unboundlocal.py: -------------------------------------------------------------------------------- 1 | #Should produce an UnboundLocal assertion 2 | #TODO: catch this exception 3 | 4 | def foo(): 5 | print(x) 6 | x = 3 7 | 8 | foo() 9 | 10 | -------------------------------------------------------------------------------- /design2/python/parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /design2/python/py-prelude.py: -------------------------------------------------------------------------------- 1 | def ___assertEqual(l, r): 2 | assert(l == r) 3 | 4 | def ___assertNotEqual(l, r): 5 | assert(not (l == r)) 6 | 7 | def ___assertTrue(v): 8 | assert(v) 9 | 10 | def ___assertFalse(v): 11 | assert(not v) 12 | 13 | def ___assertIs(l, r): 14 | assert(l is r) 15 | 16 | def ___assertIsNot(l, r): 17 | assert(not (l is r)) 18 | 19 | def ___assertIn(l, r): 20 | assert(l in r) 21 | 22 | def ___assertNotIn(l, r): 23 | assert(not (l in r)) 24 | 25 | def ___assertRaises(e, f, *args): 26 | try: 27 | f(*args) 28 | except e as the_exn: 29 | return 30 | else: 31 | assert(False) 32 | assert(False) 33 | 34 | def ___fail(): 35 | assert(False) 36 | -------------------------------------------------------------------------------- /design2/python/python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | elif t in [bytes]: return {'nodetype': 'Bytes', 'value': str(v)} 22 | else: 23 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 24 | % v) 25 | 26 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 27 | n_dict['nodetype'] = n.__class__.__name__ 28 | return n_dict 29 | 30 | if __name__ == '__main__': 31 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 32 | 33 | -------------------------------------------------------------------------------- /design2/python/python-primitives.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (require "python-core-syntax.rkt") 4 | 5 | #| 6 | 7 | Since there may end up being a large number of primitives that you 8 | implement for python, here is a suggested factoring into a separate 9 | file. You can add new primitives here by adding new symbols to the 10 | dispatch. You might also choose to add more than single-arity 11 | primitives here. 12 | 13 | |# 14 | 15 | (require (typed-in racket/base [display : (string -> void)])) 16 | 17 | (define (print [arg : CObject]) : void 18 | (display (string-append (object-str arg) "\n"))) 19 | 20 | (define (python-prim1 [op : symbol] 21 | [arg : CAnswer]) : CAnswer 22 | (type-case CAnswer arg 23 | [AObject (v s) 24 | (case op 25 | [(print) (begin 26 | (print v) 27 | arg)])] 28 | [AException (v s) (AException v s)] 29 | [else (error 'python-prim1 "unexpected result")])) 30 | 31 | ;(define (python-prim2 [op : symbol] 32 | ; [arg1 : CVal] 33 | ; [arg2 : CVal]) : CVal 34 | ; (case op 35 | ; [(Eq) ( arg)])) 36 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-callable.py: -------------------------------------------------------------------------------- 1 | ___assertIs(callable(len), True) 2 | ___assertIs(callable(1), False) 3 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-compare-list-dict.py: -------------------------------------------------------------------------------- 1 | x = [1] 2 | ___assertIs(x is x, True) 3 | ___assertIs(x is not x, False) 4 | 5 | ___assertIs(1 in x, True) 6 | ___assertIs(0 in x, False) 7 | ___assertIs(1 not in x, False) 8 | ___assertIs(0 not in x, True) 9 | 10 | x = {1: 2} 11 | ___assertIs(x is x, True) 12 | ___assertIs(x is not x, False) 13 | 14 | ___assertIs(1 in x, True) 15 | ___assertIs(0 in x, False) 16 | ___assertIs(1 not in x, False) 17 | ___assertIs(0 not in x, True) 18 | 19 | ___assertIs(not True, False) 20 | ___assertIs(not False, True) 21 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-compare.py: -------------------------------------------------------------------------------- 1 | ___assertIs(1==1, True) 2 | ___assertIs(1==0, False) 3 | ___assertIs(0<1, True) 4 | ___assertIs(1<0, False) 5 | ___assertIs(0<=0, True) 6 | ___assertIs(1<=0, False) 7 | ___assertIs(1>0, True) 8 | ___assertIs(1>1, False) 9 | ___assertIs(1>=1, True) 10 | ___assertIs(0>=1, False) 11 | ___assertIs(0!=1, True) 12 | ___assertIs(0!=0, False) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-convert.py: -------------------------------------------------------------------------------- 1 | ___assertIs(bool(10), True) 2 | ___assertIs(bool(1), True) 3 | ___assertIs(bool(-1), True) 4 | ___assertIs(bool(0), False) 5 | ___assertIs(bool("hello"), True) 6 | ___assertIs(bool(""), False) 7 | ___assertIs(bool(), False) 8 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-float.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(float(False), 0.0) 2 | ___assertIsNot(float(False), False) 3 | ___assertEqual(float(True), 1.0) 4 | ___assertIsNot(float(True), True) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-int.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(int(False), 0) 2 | ___assertIsNot(int(False), False) 3 | ___assertEqual(int(True), 1) 4 | ___assertIsNot(int(True), True) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-isinstance.py: -------------------------------------------------------------------------------- 1 | ___assertIs(isinstance(True, bool), True) 2 | ___assertIs(isinstance(False, bool), True) 3 | ___assertIs(isinstance(True, int), True) 4 | ___assertIs(isinstance(False, int), True) 5 | ___assertIs(isinstance(1, bool), False) 6 | ___assertIs(isinstance(0, bool), False) 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-math.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(+False, 0) 2 | ___assertIsNot(+False, False) 3 | ___assertEqual(-False, 0) 4 | ___assertIsNot(-False, False) 5 | ___assertEqual(abs(False), 0) 6 | ___assertIsNot(abs(False), False) 7 | ___assertEqual(+True, 1) 8 | ___assertIsNot(+True, True) 9 | ___assertEqual(-True, -1) 10 | ___assertEqual(abs(True), 1) 11 | ___assertIsNot(abs(True), True) 12 | ___assertEqual(~False, -1) 13 | ___assertEqual(~True, -2) 14 | 15 | ___assertEqual(False+2, 2) 16 | ___assertEqual(True+2, 3) 17 | ___assertEqual(2+False, 2) 18 | ___assertEqual(2+True, 3) 19 | 20 | ___assertEqual(False+False, 0) 21 | ___assertIsNot(False+False, False) 22 | ___assertEqual(False+True, 1) 23 | ___assertIsNot(False+True, True) 24 | ___assertEqual(True+False, 1) 25 | ___assertIsNot(True+False, True) 26 | ___assertEqual(True+True, 2) 27 | 28 | ___assertEqual(True-True, 0) 29 | ___assertIsNot(True-True, False) 30 | ___assertEqual(False-False, 0) 31 | ___assertIsNot(False-False, False) 32 | ___assertEqual(True-False, 1) 33 | ___assertIsNot(True-False, True) 34 | ___assertEqual(False-True, -1) 35 | 36 | ___assertEqual(True*1, 1) 37 | ___assertEqual(False*1, 0) 38 | ___assertIsNot(False*1, False) 39 | 40 | ___assertEqual(True/1, 1) 41 | ___assertIsNot(True/1, True) 42 | ___assertEqual(False/1, 0) 43 | ___assertIsNot(False/1, False) 44 | -------------------------------------------------------------------------------- /design2/python/python-reference/bool/bool-str.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(str(False), 'False') 2 | ___assertEqual(str(True), 'True') 3 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/all.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(all([2, 4, 6]), True) 2 | ___assertEqual(all([2, None, 6]), False) 3 | ___assertRaises(TypeError, all, 10) # Non-iterable 4 | ___assertRaises(TypeError, all) # No args 5 | ___assertRaises(TypeError, all, [2, 4, 6], []) # Too many args 6 | ___assertEqual(all([]), True) # Empty iterator 7 | S = [50, 60] 8 | ___assertEqual(all(x > 42 for x in S), True) 9 | S = [50, 40, 60] 10 | ___assertEqual(all(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/any.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(any([None, None, None]), False) 2 | ___assertEqual(any([None, 4, None]), True) 3 | ___assertRaises(TypeError, any, 10) # Non-iterable 4 | ___assertRaises(TypeError, any) # No args 5 | ___assertRaises(TypeError, any, [2, 4, 6], []) # Too many args 6 | ___assertEqual(any([]), False) # Empty iterator 7 | S = [40, 60, 30] 8 | ___assertEqual(any(x > 42 for x in S), True) 9 | S = [10, 20, 30] 10 | ___assertEqual(any(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/callable.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(callable(len)) 2 | ___assertFalse(callable("a")) 3 | ___assertTrue(callable(callable)) 4 | ___assertTrue(callable(lambda x, y: x + y)) 5 | 6 | def f(): pass 7 | ___assertTrue(callable(f)) 8 | 9 | class C1: 10 | def meth(self): pass 11 | ___assertTrue(callable(C1)) 12 | c = C1() 13 | ___assertTrue(callable(c.meth)) 14 | ___assertFalse(callable(c)) 15 | 16 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/filter.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) 2 | ___assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) 3 | ___assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) 4 | def badfunc(): 5 | pass 6 | ___assertRaises(TypeError, list, filter(badfunc, range(5))) 7 | 8 | # test bltinmodule.c::filtertuple() 9 | ___assertEqual(list(filter(None, (1, 2))), [1, 2]) 10 | ___assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) 11 | ___assertRaises(TypeError, list, filter(42, (1, 2))) 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/isinstance.py: -------------------------------------------------------------------------------- 1 | class C: 2 | pass 3 | class D(C): 4 | pass 5 | class E: 6 | pass 7 | c = C() 8 | d = D() 9 | e = E() 10 | ___assertTrue(isinstance(c, C)) 11 | ___assertTrue(isinstance(d, C)) 12 | ___assertTrue(not isinstance(e, C)) 13 | ___assertTrue(not isinstance(c, D)) 14 | ___assertTrue(not isinstance('foo', E)) 15 | ___assertRaises(TypeError, isinstance, E, 'foo') 16 | ___assertRaises(TypeError, isinstance) 17 | -------------------------------------------------------------------------------- /design2/python/python-reference/builtin/len.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len('123'), 3) 2 | ___assertEqual(len(()), 0) 3 | ___assertEqual(len((1, 2, 3, 4)), 4) 4 | ___assertEqual(len([1, 2, 3, 4]), 4) 5 | ___assertEqual(len({}), 0) 6 | ___assertEqual(len({'a':1, 'b': 2}), 2) 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-bool.py: -------------------------------------------------------------------------------- 1 | ___assertIs(not {}, True) 2 | ___assertTrue({1: 2}) 3 | ___assertIs(bool({}), False) 4 | ___assertIs(bool({1: 2}), True) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-clear.py: -------------------------------------------------------------------------------- 1 | d = {1:1, 2:2, 3:3} 2 | d.clear() 3 | ___assertEqual(d, {}) 4 | 5 | ___assertRaises(TypeError, d.clear, None) 6 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-contains.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertNotIn('a', d) 3 | ___assertFalse('a' in d) 4 | ___assertTrue('a' not in d) 5 | d = {'a': 1, 'b': 2} 6 | ___assertIn('a', d) 7 | ___assertIn('b', d) 8 | ___assertNotIn('c', d) 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-get.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertIs(d.get('c'), None) 3 | ___assertEqual(d.get('c', 3), 3) 4 | d = {'a': 1, 'b': 2} 5 | ___assertIs(d.get('c'), None) 6 | ___assertEqual(d.get('c', 3), 3) 7 | ___assertEqual(d.get('a'), 1) 8 | ___assertEqual(d.get('a', 3), 1) 9 | ___assertRaises(TypeError, d.get) 10 | ___assertRaises(TypeError, d.get, None, None, None) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-getitem.py: -------------------------------------------------------------------------------- 1 | d = {'a': 1, 'b': 2} 2 | ___assertEqual(d['a'], 1) 3 | ___assertEqual(d['b'], 2) 4 | d['c'] = 3 5 | d['a'] = 4 6 | ___assertEqual(d['c'], 3) 7 | ___assertEqual(d['a'], 4) 8 | del d['b'] 9 | ___assertEqual(d, {'a': 4, 'c': 3}) 10 | 11 | ___assertRaises(TypeError, d.__getitem__) 12 | 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-items.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.items()), set()) 3 | 4 | d = {1:2} 5 | ___assertEqual(set(d.items()), {(1, 2)}) 6 | ___assertRaises(TypeError, d.items, None) 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-keys.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.keys()), set()) 3 | d = {'a': 1, 'b': 2} 4 | k = d.keys() 5 | ___assertIn('a', d) 6 | ___assertIn('b', d) 7 | ___assertRaises(TypeError, d.keys, None) 8 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-set-keys.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.keys() 2 | k2 = {1:1, 2:2, 3:3}.keys() 3 | k3 = {4:4}.keys() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {1,2}) 7 | ___assertEqual(k2 - k1, {3}) 8 | ___assertEqual(k3 - k1, {4}) 9 | ___assertEqual(k1 & k2, {1,2}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {1,2,3}) 12 | ___assertEqual(k1 ^ k2, {3}) 13 | ___assertEqual(k1 ^ k3, {1,2,4}) 14 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-update.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | d.update({1:100}) 3 | d.update({2:20}) 4 | d.update({1:1, 2:2, 3:3}) 5 | ___assertEqual(d, {1:1, 2:2, 3:3}) 6 | 7 | d.update() 8 | ___assertEqual(d, {1:1, 2:2, 3:3}) 9 | 10 | ___assertRaises((TypeError, AttributeError), d.update, None) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-values-set.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.items() 2 | k2 = {1:1, 2:2, 3:3}.items() 3 | k3 = {4:4}.items() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {(1,1), (2,2)}) 7 | ___assertEqual(k2 - k1, {(3,3)}) 8 | ___assertEqual(k3 - k1, {(4,4)}) 9 | ___assertEqual(k1 & k2, {(1,1), (2,2)}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) 12 | ___assertEqual(k1 ^ k2, {(3,3)}) 13 | ___assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) 14 | -------------------------------------------------------------------------------- /design2/python/python-reference/dict/dict-values.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.values()), set()) 3 | d = {1:2} 4 | ___assertEqual(set(d.values()), {2}) 5 | ___assertRaises(TypeError, d.values, None) 6 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/except-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | except KeyError: 8 | pass 9 | raise 10 | ___assertRaises(TypeError, reraise) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/invalid-reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise 3 | except RuntimeError as e: 4 | ___assertIn("No active exception", str(e)) 5 | else: 6 | ___fail("No exception raised") 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/nested-else.py: -------------------------------------------------------------------------------- 1 | hit_else = False 2 | hit_finally = False 3 | hit_except = False 4 | hit_inner_except = False 5 | hit_inner_else = False 6 | 7 | try: 8 | try: 9 | pass 10 | except: 11 | hit_inner_except = True 12 | else: 13 | hit_inner_else = True 14 | 15 | raise Exception('outer exception') 16 | except: 17 | hit_except = True 18 | else: 19 | hit_else = True 20 | finally: 21 | hit_finally = True 22 | 23 | ___assertFalse(hit_inner_except) 24 | ___assertTrue(hit_inner_else) 25 | ___assertFalse(hit_else) 26 | ___assertTrue(hit_finally) 27 | ___assertTrue(hit_except) 28 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/nested-reraise.py: -------------------------------------------------------------------------------- 1 | def nested_reraise(): 2 | raise 3 | def reraise(): 4 | try: 5 | raise TypeError("foo") 6 | except: 7 | nested_reraise() 8 | ___assertRaises(TypeError, reraise) 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/nested.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | hit_inner_except = False 3 | hit_inner_finally = False 4 | 5 | try: 6 | try: 7 | raise Exception('inner exception') 8 | except: 9 | hit_inner_except = True 10 | finally: 11 | hit_inner_finally = True 12 | finally: 13 | hit_finally = True 14 | 15 | ___assertTrue(hit_inner_except) 16 | ___assertTrue(hit_inner_finally) 17 | ___assertTrue(hit_finally) 18 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | try: 3 | raise IndexError() 4 | except IndexError as e: 5 | exc1 = e 6 | raise 7 | except IndexError as exc2: 8 | ___assertTrue(exc1 is exc2) 9 | else: 10 | ___fail("No exception raised") 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/test-finally-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | finally: 8 | raise 9 | ___assertRaises(KeyError, reraise) 10 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/test-try-except-else.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | raise Exception('foo!') 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_else) 12 | ___assertTrue(hit_except) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/test-try-except-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | pass 5 | except: 6 | hit_except = True 7 | 8 | ___assertFalse(hit_except) 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/test-try-except.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | raise Exception('ahoy!') 5 | except: 6 | hit_except = True 7 | 8 | ___assertTrue(hit_except) 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-except-else-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | pass 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertFalse(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertTrue(hit_else) 17 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-except-else-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | raise Exception('nyaa!') 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertTrue(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertFalse(hit_else) 17 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-except-else-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_else) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-except-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-except-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | raise Exception('yarr!') 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertTrue(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/exceptions/try-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | 3 | try: 4 | pass 5 | finally: 6 | hit_finally = True 7 | 8 | ___assertTrue(hit_finally) 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/iter/iter-comprehensions.py: -------------------------------------------------------------------------------- 1 | # Test result of triple loop (too big to inline) 2 | TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), 3 | (0, 1, 0), (0, 1, 1), (0, 1, 2), 4 | (0, 2, 0), (0, 2, 1), (0, 2, 2), 5 | 6 | (1, 0, 0), (1, 0, 1), (1, 0, 2), 7 | (1, 1, 0), (1, 1, 1), (1, 1, 2), 8 | (1, 2, 0), (1, 2, 1), (1, 2, 2), 9 | 10 | (2, 0, 0), (2, 0, 1), (2, 0, 2), 11 | (2, 1, 0), (2, 1, 1), (2, 1, 2), 12 | (2, 2, 0), (2, 2, 1), (2, 2, 2)] 13 | 14 | 15 | seq = range(3) 16 | res = [] 17 | for i in iter(seq): 18 | for j in iter(seq): 19 | for k in iter(seq): 20 | res.append((i, j, k)) 21 | ___assertEqual(res, TRIPLETS) 22 | 23 | seq = range(3) 24 | res = [(i, j, k) for i in seq for j in seq for k in seq] 25 | ___assertEqual(res, TRIPLETS) 26 | -------------------------------------------------------------------------------- /design2/python/python-reference/iter/iter-misc.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | 20 | check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10))) 21 | check_for_loop(iter(range(10)), list(range(10))) 22 | check_for_loop(iter("abcde"), ["a", "b", "c", "d", "e"]) 23 | 24 | dict = {} 25 | for i in range(10): 26 | dict[i] = None 27 | check_for_loop(dict, list(dict.keys())) 28 | -------------------------------------------------------------------------------- /design2/python/python-reference/iter/iter-simple.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | # Test basic use of iter() function 20 | check_iterator(iter(range(10)), list(range(10))) 21 | 22 | # Test that iter(iter(x)) is the same as iter(x) 23 | seq = list(range(10)) 24 | it = iter(seq) 25 | it2 = iter(it) 26 | ___assertTrue(it is it2) 27 | 28 | check_for_loop(iter(range(10)), list(range(10))) 29 | 30 | check_for_loop(iter([]), []) 31 | -------------------------------------------------------------------------------- /design2/python/python-reference/lists/test_list_identity.py: -------------------------------------------------------------------------------- 1 | if(not ([] is not [])): raise Exception('list identity') 2 | -------------------------------------------------------------------------------- /design2/python/python-reference/lists/test_list_simple.py: -------------------------------------------------------------------------------- 1 | if (not (list([]) == [])): raise Exception('List empty') 2 | l0_3 = [0, 1, 2, 3] 3 | l0_3_bis = list(l0_3) 4 | if (not (l0_3 == l0_3_bis)): raise Exception('List identity') 5 | if (not (l0_3 is not l0_3_bis)): raise Exception('List identity') 6 | if (not (list(()) == [])): raise Exception( 'List tuple') 7 | if (not (list((0, 1, 2, 3)), [0, 1, 2, 3])): raise Exception('List tuple 2') 8 | if (not (list('') == [])): raise Exception( 'List string 1') 9 | if (not (list('spam') == ['s', 'p', 'a', 'm'])): raise Exception( 'List string 2') 10 | 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/lists/test_list_truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not []) 2 | ___assertTrue([42]) 3 | -------------------------------------------------------------------------------- /design2/python/python-reference/range/range-errs.py: -------------------------------------------------------------------------------- 1 | ___assertRaises(TypeError, range) 2 | ___assertRaises(TypeError, range, 1, 2, 3, 4) 3 | ___assertRaises(ValueError, range, 1, 2, 0) 4 | 5 | ___assertRaises(TypeError, range, 0.0, 2, 1) 6 | ___assertRaises(TypeError, range, 1, 2.0, 1) 7 | ___assertRaises(TypeError, range, 1, 2, 1.0) 8 | ___assertRaises(TypeError, range, 1e100, 1e101, 1e101) 9 | 10 | ___assertRaises(TypeError, range, 0, "spam") 11 | ___assertRaises(TypeError, range, 0, 42, "spam") 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/range/range-list.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(range(3)), [0, 1, 2]) 2 | ___assertEqual(list(range(1, 5)), [1, 2, 3, 4]) 3 | ___assertEqual(list(range(0)), []) 4 | ___assertEqual(list(range(-3)), []) 5 | ___assertEqual(list(range(1, 10, 3)), [1, 4, 7]) 6 | ___assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/range/range-vars.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | b = 100 3 | c = 50 4 | 5 | ___assertEqual(list(range(a, a+2)), [a, a+1]) 6 | ___assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) 7 | ___assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) 8 | 9 | seq = list(range(a, b, c)) 10 | ___assertIn(a, seq) 11 | ___assertNotIn(b, seq) 12 | ___assertEqual(len(seq), 2) 13 | 14 | seq = list(range(b, a, -c)) 15 | ___assertIn(b, seq) 16 | ___assertNotIn(a, seq) 17 | ___assertEqual(len(seq), 2) 18 | 19 | seq = list(range(-a, -b, -c)) 20 | ___assertIn(-a, seq) 21 | ___assertNotIn(-b, seq) 22 | ___assertEqual(len(seq), 2) 23 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/bound-and-free.py: -------------------------------------------------------------------------------- 1 | # var is bound and free in class 2 | 3 | def f(x): 4 | class C: 5 | def m(self): 6 | return x 7 | a = x 8 | return C 9 | 10 | inst = f(3)() 11 | ___assertEqual(inst.a, inst.m()) 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/extra-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder2(x): 2 | def extra(): # check freevars passing through non-use scopes 3 | def adder(y): 4 | return x + y 5 | return adder 6 | return extra() 7 | 8 | inc = make_adder2(1) 9 | plus10 = make_adder2(10) 10 | 11 | ___assertEqual(inc(1), 2) 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/freevar-in-method.py: -------------------------------------------------------------------------------- 1 | def test(): 2 | method_and_var = "var" 3 | class Test: 4 | def method_and_var(self): 5 | return "method" 6 | def test(self): 7 | return method_and_var 8 | def actual_global(self): 9 | return str("global") 10 | def str(self): 11 | return str(self) 12 | return Test() 13 | 14 | t = test() 15 | ___assertEqual(t.test(), "var") 16 | ___assertEqual(t.method_and_var(), "method") 17 | ___assertEqual(t.actual_global(), "global") 18 | 19 | method_and_var = "var" 20 | class Test: 21 | # this class is not nested, so the rules are different 22 | def method_and_var(self): 23 | return "method" 24 | def test(self): 25 | return method_and_var 26 | def actual_global(self): 27 | return str("global") 28 | def str(self): 29 | return str(self) 30 | 31 | t = Test() 32 | ___assertEqual(t.test(), "var") 33 | ___assertEqual(t.method_and_var(), "method") 34 | ___assertEqual(t.actual_global(), "global") 35 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/lambda1.py: -------------------------------------------------------------------------------- 1 | f1 = lambda x: lambda y: x + y 2 | inc = f1(1) 3 | plus10 = f1(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/lambda2.py: -------------------------------------------------------------------------------- 1 | f2 = lambda x: (lambda : lambda y: x + y)() 2 | inc = f2(1) 3 | plus10 = f2(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/lambda3.py: -------------------------------------------------------------------------------- 1 | f3 = lambda x: lambda y: global_x + y 2 | global_x = 1 3 | inc = f3(None) 4 | ___assertEqual(inc(2), 3) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/lambda4.py: -------------------------------------------------------------------------------- 1 | f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) 2 | g = f8(1, 2, 3) 3 | h = g(2, 4, 6) 4 | ___assertEqual(h(), 18) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/locals-class.py: -------------------------------------------------------------------------------- 1 | # This test verifies that calling locals() does not pollute 2 | # the local namespace of the class with free variables. Old 3 | # versions of Python had a bug, where a free variable being 4 | # passed through a class namespace would be inserted into 5 | # locals() by locals() or exec or a trace function. 6 | # 7 | # The real bug lies in frame code that copies variables 8 | # between fast locals and the locals dict, e.g. when executing 9 | # a trace function. 10 | 11 | def f(x): 12 | class C: 13 | x = 12 14 | def m(self): 15 | return x 16 | locals() 17 | return C 18 | 19 | ___assertEqual(f(1).x, 12) 20 | 21 | def f(x): 22 | class C: 23 | y = x 24 | def m(self): 25 | return x 26 | z = list(locals()) 27 | return C 28 | 29 | varnames = f(1).z 30 | ___assertNotIn("x", varnames) 31 | ___assertIn("y", varnames) 32 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/locals-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | def h(z): 4 | return y + z 5 | w = x + y 6 | y += 3 7 | return locals() 8 | return g 9 | 10 | d = f(2)(4) 11 | ___assertIn('h', d) 12 | del d['h'] 13 | ___assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) 14 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/mixed-freevars-and-cellvars.py: -------------------------------------------------------------------------------- 1 | def identity(x): 2 | return x 3 | 4 | def f(x, y, z): 5 | def g(a, b, c): 6 | a = a + x # 3 7 | def h(): 8 | # z * (4 + 9) 9 | # 3 * 13 10 | return identity(z * (b + y)) 11 | y = c + z # 9 12 | return h 13 | return g 14 | 15 | g = f(1, 2, 3) 16 | h = g(2, 4, 6) 17 | ___assertEqual(h(), 39) 18 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nearest-enclosing-scope.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | x = 42 # check that this masks binding in f() 4 | def h(z): 5 | return x + z 6 | return h 7 | return g(2) 8 | 9 | test_func = f(10) 10 | ___assertEqual(test_func(5), 47) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nested-nonlocal.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(): 3 | nonlocal x 4 | x -= 2 5 | def h(): 6 | nonlocal x 7 | x += 4 8 | return x 9 | return h 10 | return g 11 | 12 | g = f(1) 13 | h = g() 14 | ___assertEqual(h(), 3) 15 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nesting-global-no-free.py: -------------------------------------------------------------------------------- 1 | def make_adder4(): # XXX add exta level of indirection 2 | def nest(): 3 | def nest(): 4 | def adder(y): 5 | return global_x + y # check that plain old globals work 6 | return adder 7 | return nest() 8 | return nest() 9 | 10 | global_x = 1 11 | adder = make_adder4() 12 | ___assertEqual(adder(1), 2) 13 | 14 | global_x = 10 15 | ___assertEqual(adder(-2), 8) 16 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nesting-plus-free-ref-to-global.py: -------------------------------------------------------------------------------- 1 | def make_adder6(x): 2 | global global_nest_x 3 | def adder(y): 4 | return global_nest_x + y 5 | global_nest_x = x 6 | return adder 7 | 8 | inc = make_adder6(1) 9 | plus10 = make_adder6(10) 10 | 11 | ___assertEqual(inc(1), 11) # there's only one global 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nesting-through-class.py: -------------------------------------------------------------------------------- 1 | def make_adder5(x): 2 | class Adder: 3 | def __call__(self, y): 4 | return x + y 5 | return Adder() 6 | 7 | inc = make_adder5(1) 8 | plus10 = make_adder5(10) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nonlocal-class.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | nonlocal x 4 | x += 1 5 | def get(self): 6 | return x 7 | return c() 8 | 9 | c = f(0) 10 | ___assertEqual(c.get(), 1) 11 | ___assertNotIn("x", c.__class__.__dict__) 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nonlocal-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def inc(): 3 | nonlocal x 4 | x += 1 5 | return x 6 | def dec(): 7 | nonlocal x 8 | x -= 1 9 | return x 10 | return inc, dec 11 | 12 | inc, dec = f(0) 13 | ___assertEqual(inc(), 1) 14 | ___assertEqual(inc(), 2) 15 | ___assertEqual(dec(), 1) 16 | ___assertEqual(dec(), 0) 17 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/nonlocal-method.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | def inc(self): 4 | nonlocal x 5 | x += 1 6 | return x 7 | def dec(self): 8 | nonlocal x 9 | x -= 1 10 | return x 11 | return c() 12 | c = f(0) 13 | ___assertEqual(c.inc(), 1) 14 | ___assertEqual(c.inc(), 2) 15 | ___assertEqual(c.dec(), 1) 16 | ___assertEqual(c.dec(), 0) 17 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/recursion.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def fact(n): 3 | if n == 0: 4 | return 1 5 | else: 6 | return n * fact(n - 1) 7 | if x >= 0: 8 | return fact(x) 9 | else: 10 | raise ValueError("x must be >= 0") 11 | 12 | ___assertEqual(f(6), 720) 13 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/simple-and-rebinding.py: -------------------------------------------------------------------------------- 1 | def make_adder3(x): 2 | def adder(y): 3 | return x + y 4 | x = x + 1 # check tracking of assignment to x in defining scope 5 | return adder 6 | 7 | inc = make_adder3(0) 8 | plus10 = make_adder3(9) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/simple-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder(x): 2 | def adder(y): 3 | return x + y 4 | return adder 5 | 6 | inc = make_adder(1) 7 | plus10 = make_adder(10) 8 | 9 | ___assertEqual(inc(1), 2) 10 | ___assertEqual(plus10(-2), 8) 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/scope/unbound-local.py: -------------------------------------------------------------------------------- 1 | def errorInOuter(): 2 | print(y) 3 | def inner(): 4 | return y 5 | y = 1 6 | 7 | def errorInInner(): 8 | def inner(): 9 | return y 10 | inner() 11 | y = 1 12 | 13 | ___assertRaises(UnboundLocalError, errorInOuter) 14 | ___assertRaises(NameError, errorInInner) 15 | -------------------------------------------------------------------------------- /design2/python/python-reference/tuple/tuple-add.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u += (2, 3) 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/tuple/tuple-constructors.py: -------------------------------------------------------------------------------- 1 | # calling built-in types without argument must return empty 2 | ___assertEqual(tuple(), ()) 3 | t0_3 = (0, 1, 2, 3) 4 | t0_3_bis = tuple(t0_3) 5 | ___assertTrue(t0_3 is t0_3_bis) 6 | ___assertEqual(tuple([]), ()) 7 | ___assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) 8 | ___assertEqual(tuple(''), ()) 9 | ___assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) 10 | -------------------------------------------------------------------------------- /design2/python/python-reference/tuple/tuple-length.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len(()), 0) 2 | ___assertEqual(len((0,)), 1) 3 | ___assertEqual(len((0, 1, 2)), 3) 4 | -------------------------------------------------------------------------------- /design2/python/python-reference/tuple/tuple-mul.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u *= 3 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/tuple/tuple-truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not ()) 2 | ___assertTrue((42, )) 3 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_booleans.py: -------------------------------------------------------------------------------- 1 | if 0 or 0: raise Exception('0 or 0 is true instead of false') 2 | if 1 and 1: pass 3 | else: raise Exception('1 and 1 is false instead of true') 4 | if not 1: raise Exception('not 1 is true instead of false') 5 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_comparisons.py: -------------------------------------------------------------------------------- 1 | if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass 2 | else: raise Exception('int comparisons failed') 3 | if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass 4 | else: raise Exception('float comparisons failed') 5 | if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass 6 | else: raise Exception('string comparisons failed') 7 | if None is None: pass 8 | else: raise Exception('identity test failed') 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_div_zero.py: -------------------------------------------------------------------------------- 1 | try: 5.0 / 0.0 2 | except ZeroDivisionError: pass 3 | else: raise Exception("5.0 / 0.0 didn't raise ZeroDivisionError") 4 | 5 | try: 5.0 // 0.0 6 | except ZeroDivisionError: pass 7 | else: raise Exception("5.0 // 0.0 didn't raise ZeroDivisionError") 8 | 9 | try: 5.0 % 0.0 10 | except ZeroDivisionError: pass 11 | else: raise Exception("5.0 % 0.0 didn't raise ZeroDivisionError") 12 | 13 | try: 5 / 0 14 | except ZeroDivisionError: pass 15 | else: raise Exception("5 / 0 didn't raise ZeroDivisionError") 16 | 17 | try: 5 // 0 18 | except ZeroDivisionError: pass 19 | else: raise Exception("5 // 0 didn't raise ZeroDivisionError") 20 | 21 | try: 5 % 0 22 | except ZeroDivisionError: pass 23 | else: raise Exception("5 % 0 didn't raise ZeroDivisionError") 24 | 25 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_floats.py: -------------------------------------------------------------------------------- 1 | if 12.0 + 24.0 != 36.0: raise Exception('float op +') 2 | if 12.0 + (-24.0) != -12.0: raise Exception('float op +/-') 3 | if (-12.0) + 24.0 != 12.0: raise Exception('float op -/+') 4 | if (-12.0) + (-24.0) != -36.0: raise Exception('float op -/+/-') 5 | if not 12.0 < 24.0: raise Exception('float op <') 6 | if not -24.0 < -12.0: raise Exception('float op < negative') 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_simple_string_ops.py: -------------------------------------------------------------------------------- 1 | if 'xyz' + 'abcde' != 'xyzabcde': raise Exception('string concatenation') 2 | if 'xyz'*3 != 'xyzxyzxyz': raise Exception('string repetition *3') 3 | if 0*'abcde' != '': raise Exception('string repetition 0*') 4 | if min('abc') != 'a' or max('abc') != 'c': raise Exception('min/max string') 5 | if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass 6 | else: raise Exception('in/not in string') 7 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_simple_strings.py: -------------------------------------------------------------------------------- 1 | if len('') != 0: raise Exception('len(\'\')') 2 | if len('a') != 1: raise Exception('len(\'a\')') 3 | if len('abcdef') != 6: raise Exception('len(\'abcdef\')') 4 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/test_string_slices.py: -------------------------------------------------------------------------------- 1 | a = '0123456789' 2 | if (not (a[::] == a)): raise Exception('Slice total') 3 | if (not (a[::2] == '02468')): raise Exception('Slice 2') 4 | if (not (a[1::2] == '13579')): raise Exception('Slice 1::2') 5 | if (not (a[::-1] =='9876543210')): raise Exception('Slice ::-1') 6 | if (not (a[::-2] == '97531')): raise Exception('Slice ::-2') 7 | if (not (a[3::-2] == '31')): raise Exception('Slice 3::-2') 8 | if (not (a[-100:100:] == a)): raise Exception('Slice -100::100') 9 | if (not (a[100:-100:-1] == a[::-1])): raise Exception('Slice triple') 10 | if (not (a[-100:100:2] == '02468')): raise Exception('Slice triple 2') 11 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/types_truthy1.py: -------------------------------------------------------------------------------- 1 | if None: raise Exception('None is true instead of false') 2 | if 0: raise Exception('0 is true instead of false') 3 | if 0.0: raise Exception('0.0 is true instead of false') 4 | if '': raise Exception('\'\' is true instead of false') 5 | if not 1: raise Exception('1 is false instead of true') 6 | if not 1.0: raise Exception('1.0 is false instead of true') 7 | if not 'x': raise Exception('\'x\' is false instead of true') 8 | if not {'x': 1}: raise Exception('{\'x\': 1} is false instead of true') 9 | -------------------------------------------------------------------------------- /design2/python/python-reference/types/types_truthy2.py: -------------------------------------------------------------------------------- 1 | def f(): pass 2 | class C: pass 3 | x = C() 4 | if not f: raise Exception('f is false instead of true') 5 | if not C: raise Exception('C is false instead of true') 6 | if not x: raise Exception('x is false instead of true') 7 | -------------------------------------------------------------------------------- /design2/python/python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (define-type PyExpr 4 | [PyGlobal (names : (listof symbol))] 5 | [PyNonlocal (names : (listof symbol))] 6 | [PySeq (es : (listof PyExpr))] 7 | [PyAssign (value : PyExpr) (targets : (listof symbol))] 8 | [PyReal (n : number)] 9 | [PyPass] 10 | [PyStr (s : string)] 11 | [PyComplex (n : number)] 12 | [PyFunc (id : symbol) (args : (listof symbol)) (body : PyExpr)] 13 | [PyReturn (value : PyExpr)] 14 | ;[PyTryFinally (body : PyExpr) (finally : PyExpr)] ; Always runs 'finally' on exit of body 15 | ;[PyTryCatch (body : PyExpr) (handlers : (listof) (orelse : PyExpr)] ; 16 | [PyId (x : symbol)] 17 | [PyIf (tst : PyExpr) (thn : PyExpr) (els : PyExpr)] 18 | [PyApp (fun : PyExpr) (args : (listof PyExpr))]) 19 | 20 | 21 | -------------------------------------------------------------------------------- /design2/python/run.sh: -------------------------------------------------------------------------------- 1 | racket python-main.rkt --python-path "c:\\cygwin\bin\\python3.2m.exe" $* 2 | -------------------------------------------------------------------------------- /design2/python/test.py: -------------------------------------------------------------------------------- 1 | def divide(x, y): 2 | try: 3 | result = x / y 4 | except (ZeroDivisionError, UnboundLocalError): 5 | print("division by zero!") 6 | except Exception: 7 | print("exception") 8 | else: 9 | print("result is", result) 10 | finally: 11 | print("executing finally clause") 12 | 13 | -------------------------------------------------------------------------------- /design2/python/test.sh: -------------------------------------------------------------------------------- 1 | ./run.sh --test $* 2 | -------------------------------------------------------------------------------- /design2/python/test2.py: -------------------------------------------------------------------------------- 1 | #class MyClass: 2 | # a = "hello" 3 | # def f(self): 4 | # print("self.a: ") 5 | # print(self.a); 6 | # print(type(self)) 7 | # 8 | # class MySubClass: 9 | # nonlocal a 10 | # b = "world" 11 | # def f(self): 12 | # print("self.a: ") 13 | # print(self.a); 14 | # print("self.b: ") 15 | # print(self.b); 16 | # print(type(self)) 17 | # 18 | #c = MyClass.MySubClass(); 19 | #c.f(); 20 | 21 | class TestClass: 22 | a = "hello" 23 | 24 | print(type(TestClass)) 25 | 26 | def my(): 27 | def foo(): 28 | def bar(): 29 | global x 30 | print(x) 31 | 32 | my() 33 | 34 | -------------------------------------------------------------------------------- /design3/cs173-python/.gitignore: -------------------------------------------------------------------------------- 1 | compiled/ 2 | *.swp 3 | *~ 4 | -------------------------------------------------------------------------------- /design3/cs173-python/parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /design3/cs173-python/py-prelude.py: -------------------------------------------------------------------------------- 1 | def ___assertEqual(l, r): 2 | assert(l == r) 3 | 4 | def ___assertNotEqual(l, r): 5 | assert(not (l == r)) 6 | 7 | def ___assertTrue(v): 8 | assert(v) 9 | 10 | def ___assertFalse(v): 11 | assert(not v) 12 | 13 | def ___assertIs(l, r): 14 | assert(l is r) 15 | 16 | def ___assertIsNot(l, r): 17 | assert(not (l is r)) 18 | 19 | def ___assertIn(l, r): 20 | assert(l in r) 21 | 22 | def ___assertNotIn(l, r): 23 | assert(not (l in r)) 24 | 25 | def ___assertRaises(e, f, *args): 26 | try: 27 | f(*args) 28 | except e as the_exn: 29 | return 30 | else: 31 | assert(False) 32 | assert(False) 33 | 34 | def ___fail(): 35 | assert(False) 36 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/basic.py: -------------------------------------------------------------------------------- 1 | x=4 2 | print(x) 3 | 4 | def f(x): 5 | y=4 6 | return x 7 | 8 | print(f(5)) 9 | 10 | def g(x): 11 | x 12 | 13 | print(g(5)) 14 | 15 | ___assertTrue(1) 16 | ___assertTrue(False) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/funcs.py: -------------------------------------------------------------------------------- 1 | x=4 2 | f=lambda x: x 3 | print(f(4)) 4 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/if-then-else.py: -------------------------------------------------------------------------------- 1 | if 0: 2 | print(0) 3 | else: 4 | print(1) 5 | 6 | if True: 7 | print(1) 8 | else: 9 | print(0) 10 | 11 | if False: 12 | print(0) 13 | else: 14 | print(1) 15 | 16 | x=() 17 | 18 | if x: 19 | print(0) 20 | else: 21 | print(1) 22 | 23 | if (1,2): 24 | print(1) 25 | else: 26 | print(0) 27 | 28 | if None: 29 | print(0) 30 | else: 31 | print(1) 32 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/if-then.py: -------------------------------------------------------------------------------- 1 | if 1: 2 | print(4) 3 | 4 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/nonlocal.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | x=4 3 | def g(): 4 | def h(): 5 | nonlocal x 6 | x+=2 7 | h() 8 | g() 9 | print(x) 10 | f() 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-examples/varargs.py: -------------------------------------------------------------------------------- 1 | x = (1,2,3) 2 | 3 | def f(x,y,*z): 4 | print(x+y) 5 | print(z) 6 | 7 | f(1,*x) 8 | -------------------------------------------------------------------------------- /design3/cs173-python/python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | else: 22 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 23 | % v) 24 | 25 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 26 | n_dict['nodetype'] = n.__class__.__name__ 27 | return n_dict 28 | 29 | if __name__ == '__main__': 30 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 31 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-callable.py: -------------------------------------------------------------------------------- 1 | ___assertIs(callable(len), True) 2 | ___assertIs(callable(1), False) 3 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-compare-list-dict.py: -------------------------------------------------------------------------------- 1 | x = [1] 2 | ___assertIs(x is x, True) 3 | ___assertIs(x is not x, False) 4 | 5 | ___assertIs(1 in x, True) 6 | ___assertIs(0 in x, False) 7 | ___assertIs(1 not in x, False) 8 | ___assertIs(0 not in x, True) 9 | 10 | x = {1: 2} 11 | ___assertIs(x is x, True) 12 | ___assertIs(x is not x, False) 13 | 14 | ___assertIs(1 in x, True) 15 | ___assertIs(0 in x, False) 16 | ___assertIs(1 not in x, False) 17 | ___assertIs(0 not in x, True) 18 | 19 | ___assertIs(not True, False) 20 | ___assertIs(not False, True) 21 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-compare.py: -------------------------------------------------------------------------------- 1 | ___assertIs(1==1, True) 2 | ___assertIs(1==0, False) 3 | ___assertIs(0<1, True) 4 | ___assertIs(1<0, False) 5 | ___assertIs(0<=0, True) 6 | ___assertIs(1<=0, False) 7 | ___assertIs(1>0, True) 8 | ___assertIs(1>1, False) 9 | ___assertIs(1>=1, True) 10 | ___assertIs(0>=1, False) 11 | ___assertIs(0!=1, True) 12 | ___assertIs(0!=0, False) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-convert.py: -------------------------------------------------------------------------------- 1 | ___assertIs(bool(10), True) 2 | ___assertIs(bool(1), True) 3 | ___assertIs(bool(-1), True) 4 | ___assertIs(bool(0), False) 5 | ___assertIs(bool("hello"), True) 6 | ___assertIs(bool(""), False) 7 | ___assertIs(bool(), False) 8 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-float.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(float(False), 0.0) 2 | ___assertIsNot(float(False), False) 3 | ___assertEqual(float(True), 1.0) 4 | ___assertIsNot(float(True), True) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-int.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(int(False), 0) 2 | ___assertIsNot(int(False), False) 3 | ___assertEqual(int(True), 1) 4 | ___assertIsNot(int(True), True) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-isinstance.py: -------------------------------------------------------------------------------- 1 | ___assertIs(isinstance(True, bool), True) 2 | ___assertIs(isinstance(False, bool), True) 3 | ___assertIs(isinstance(True, int), True) 4 | ___assertIs(isinstance(False, int), True) 5 | ___assertIs(isinstance(1, bool), False) 6 | ___assertIs(isinstance(0, bool), False) 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-math.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(+False, 0) 2 | ___assertIsNot(+False, False) 3 | ___assertEqual(-False, 0) 4 | ___assertIsNot(-False, False) 5 | ___assertEqual(abs(False), 0) 6 | ___assertIsNot(abs(False), False) 7 | ___assertEqual(+True, 1) 8 | ___assertIsNot(+True, True) 9 | ___assertEqual(-True, -1) 10 | ___assertEqual(abs(True), 1) 11 | ___assertIsNot(abs(True), True) 12 | ___assertEqual(~False, -1) 13 | ___assertEqual(~True, -2) 14 | 15 | ___assertEqual(False+2, 2) 16 | ___assertEqual(True+2, 3) 17 | ___assertEqual(2+False, 2) 18 | ___assertEqual(2+True, 3) 19 | 20 | ___assertEqual(False+False, 0) 21 | ___assertIsNot(False+False, False) 22 | ___assertEqual(False+True, 1) 23 | ___assertIsNot(False+True, True) 24 | ___assertEqual(True+False, 1) 25 | ___assertIsNot(True+False, True) 26 | ___assertEqual(True+True, 2) 27 | 28 | ___assertEqual(True-True, 0) 29 | ___assertIsNot(True-True, False) 30 | ___assertEqual(False-False, 0) 31 | ___assertIsNot(False-False, False) 32 | ___assertEqual(True-False, 1) 33 | ___assertIsNot(True-False, True) 34 | ___assertEqual(False-True, -1) 35 | 36 | ___assertEqual(True*1, 1) 37 | ___assertEqual(False*1, 0) 38 | ___assertIsNot(False*1, False) 39 | 40 | ___assertEqual(True/1, 1) 41 | ___assertIsNot(True/1, True) 42 | ___assertEqual(False/1, 0) 43 | ___assertIsNot(False/1, False) 44 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/bool/bool-str.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(str(False), 'False') 2 | ___assertEqual(str(True), 'True') 3 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/all.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(all([2, 4, 6]), True) 2 | ___assertEqual(all([2, None, 6]), False) 3 | ___assertRaises(TypeError, all, 10) # Non-iterable 4 | ___assertRaises(TypeError, all) # No args 5 | ___assertRaises(TypeError, all, [2, 4, 6], []) # Too many args 6 | ___assertEqual(all([]), True) # Empty iterator 7 | S = [50, 60] 8 | ___assertEqual(all(x > 42 for x in S), True) 9 | S = [50, 40, 60] 10 | ___assertEqual(all(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/any.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(any([None, None, None]), False) 2 | ___assertEqual(any([None, 4, None]), True) 3 | ___assertRaises(TypeError, any, 10) # Non-iterable 4 | ___assertRaises(TypeError, any) # No args 5 | ___assertRaises(TypeError, any, [2, 4, 6], []) # Too many args 6 | ___assertEqual(any([]), False) # Empty iterator 7 | S = [40, 60, 30] 8 | ___assertEqual(any(x > 42 for x in S), True) 9 | S = [10, 20, 30] 10 | ___assertEqual(any(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/callable.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(callable(len)) 2 | ___assertFalse(callable("a")) 3 | ___assertTrue(callable(callable)) 4 | ___assertTrue(callable(lambda x, y: x + y)) 5 | 6 | def f(): pass 7 | ___assertTrue(callable(f)) 8 | 9 | class C1: 10 | def meth(self): pass 11 | ___assertTrue(callable(C1)) 12 | c = C1() 13 | ___assertTrue(callable(c.meth)) 14 | ___assertFalse(callable(c)) 15 | 16 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/filter.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) 2 | ___assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) 3 | ___assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) 4 | def badfunc(): 5 | pass 6 | ___assertRaises(TypeError, list, filter(badfunc, range(5))) 7 | 8 | # test bltinmodule.c::filtertuple() 9 | ___assertEqual(list(filter(None, (1, 2))), [1, 2]) 10 | ___assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) 11 | ___assertRaises(TypeError, list, filter(42, (1, 2))) 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/isinstance.py: -------------------------------------------------------------------------------- 1 | class C: 2 | pass 3 | class D(C): 4 | pass 5 | class E: 6 | pass 7 | c = C() 8 | d = D() 9 | e = E() 10 | ___assertTrue(isinstance(c, C)) 11 | ___assertTrue(isinstance(d, C)) 12 | ___assertTrue(not isinstance(e, C)) 13 | ___assertTrue(not isinstance(c, D)) 14 | ___assertTrue(not isinstance('foo', E)) 15 | ___assertRaises(TypeError, isinstance, E, 'foo') 16 | ___assertRaises(TypeError, isinstance) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/builtin/len.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len('123'), 3) 2 | ___assertEqual(len(()), 0) 3 | ___assertEqual(len((1, 2, 3, 4)), 4) 4 | ___assertEqual(len([1, 2, 3, 4]), 4) 5 | ___assertEqual(len({}), 0) 6 | ___assertEqual(len({'a':1, 'b': 2}), 2) 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-bool.py: -------------------------------------------------------------------------------- 1 | ___assertIs(not {}, True) 2 | ___assertTrue({1: 2}) 3 | ___assertIs(bool({}), False) 4 | ___assertIs(bool({1: 2}), True) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-clear.py: -------------------------------------------------------------------------------- 1 | d = {1:1, 2:2, 3:3} 2 | d.clear() 3 | ___assertEqual(d, {}) 4 | 5 | ___assertRaises(TypeError, d.clear, None) 6 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-contains.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertNotIn('a', d) 3 | ___assertFalse('a' in d) 4 | ___assertTrue('a' not in d) 5 | d = {'a': 1, 'b': 2} 6 | ___assertIn('a', d) 7 | ___assertIn('b', d) 8 | ___assertNotIn('c', d) 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-get.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertIs(d.get('c'), None) 3 | ___assertEqual(d.get('c', 3), 3) 4 | d = {'a': 1, 'b': 2} 5 | ___assertIs(d.get('c'), None) 6 | ___assertEqual(d.get('c', 3), 3) 7 | ___assertEqual(d.get('a'), 1) 8 | ___assertEqual(d.get('a', 3), 1) 9 | ___assertRaises(TypeError, d.get) 10 | ___assertRaises(TypeError, d.get, None, None, None) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-getitem.py: -------------------------------------------------------------------------------- 1 | d = {'a': 1, 'b': 2} 2 | ___assertEqual(d['a'], 1) 3 | ___assertEqual(d['b'], 2) 4 | d['c'] = 3 5 | d['a'] = 4 6 | ___assertEqual(d['c'], 3) 7 | ___assertEqual(d['a'], 4) 8 | del d['b'] 9 | ___assertEqual(d, {'a': 4, 'c': 3}) 10 | 11 | ___assertRaises(TypeError, d.__getitem__) 12 | 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-items.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.items()), set()) 3 | 4 | d = {1:2} 5 | ___assertEqual(set(d.items()), {(1, 2)}) 6 | ___assertRaises(TypeError, d.items, None) 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-keys.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.keys()), set()) 3 | d = {'a': 1, 'b': 2} 4 | k = d.keys() 5 | ___assertIn('a', d) 6 | ___assertIn('b', d) 7 | ___assertRaises(TypeError, d.keys, None) 8 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-set-keys.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.keys() 2 | k2 = {1:1, 2:2, 3:3}.keys() 3 | k3 = {4:4}.keys() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {1,2}) 7 | ___assertEqual(k2 - k1, {3}) 8 | ___assertEqual(k3 - k1, {4}) 9 | ___assertEqual(k1 & k2, {1,2}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {1,2,3}) 12 | ___assertEqual(k1 ^ k2, {3}) 13 | ___assertEqual(k1 ^ k3, {1,2,4}) 14 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-update.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | d.update({1:100}) 3 | d.update({2:20}) 4 | d.update({1:1, 2:2, 3:3}) 5 | ___assertEqual(d, {1:1, 2:2, 3:3}) 6 | 7 | d.update() 8 | ___assertEqual(d, {1:1, 2:2, 3:3}) 9 | 10 | ___assertRaises((TypeError, AttributeError), d.update, None) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-values-set.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.items() 2 | k2 = {1:1, 2:2, 3:3}.items() 3 | k3 = {4:4}.items() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {(1,1), (2,2)}) 7 | ___assertEqual(k2 - k1, {(3,3)}) 8 | ___assertEqual(k3 - k1, {(4,4)}) 9 | ___assertEqual(k1 & k2, {(1,1), (2,2)}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) 12 | ___assertEqual(k1 ^ k2, {(3,3)}) 13 | ___assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) 14 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/dict/dict-values.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.values()), set()) 3 | d = {1:2} 4 | ___assertEqual(set(d.values()), {2}) 5 | ___assertRaises(TypeError, d.values, None) 6 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/except-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | except KeyError: 8 | pass 9 | raise 10 | ___assertRaises(TypeError, reraise) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/invalid-reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise 3 | except RuntimeError as e: 4 | ___assertIn("No active exception", str(e)) 5 | else: 6 | ___fail("No exception raised") 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/nested-else.py: -------------------------------------------------------------------------------- 1 | hit_else = False 2 | hit_finally = False 3 | hit_except = False 4 | hit_inner_except = False 5 | hit_inner_else = False 6 | 7 | try: 8 | try: 9 | pass 10 | except: 11 | hit_inner_except = True 12 | else: 13 | hit_inner_else = True 14 | 15 | raise Exception('outer exception') 16 | except: 17 | hit_except = True 18 | else: 19 | hit_else = True 20 | finally: 21 | hit_finally = True 22 | 23 | ___assertFalse(hit_inner_except) 24 | ___assertTrue(hit_inner_else) 25 | ___assertFalse(hit_else) 26 | ___assertTrue(hit_finally) 27 | ___assertTrue(hit_except) 28 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/nested-reraise.py: -------------------------------------------------------------------------------- 1 | def nested_reraise(): 2 | raise 3 | def reraise(): 4 | try: 5 | raise TypeError("foo") 6 | except: 7 | nested_reraise() 8 | ___assertRaises(TypeError, reraise) 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/nested.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | hit_inner_except = False 3 | hit_inner_finally = False 4 | 5 | try: 6 | try: 7 | raise Exception('inner exception') 8 | except: 9 | hit_inner_except = True 10 | finally: 11 | hit_inner_finally = True 12 | finally: 13 | hit_finally = True 14 | 15 | ___assertTrue(hit_inner_except) 16 | ___assertTrue(hit_inner_finally) 17 | ___assertTrue(hit_finally) 18 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | try: 3 | raise IndexError() 4 | except IndexError as e: 5 | exc1 = e 6 | raise 7 | except IndexError as exc2: 8 | ___assertTrue(exc1 is exc2) 9 | else: 10 | ___fail("No exception raised") 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/test-finally-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | finally: 8 | raise 9 | ___assertRaises(KeyError, reraise) 10 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/test-try-except-else.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | raise Exception('foo!') 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_else) 12 | ___assertTrue(hit_except) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/test-try-except-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | pass 5 | except: 6 | hit_except = True 7 | 8 | ___assertFalse(hit_except) 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/test-try-except.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | raise Exception('ahoy!') 5 | except: 6 | hit_except = True 7 | 8 | ___assertTrue(hit_except) 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-except-else-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | pass 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertFalse(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertTrue(hit_else) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-except-else-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | raise Exception('nyaa!') 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertTrue(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertFalse(hit_else) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-except-else-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_else) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-except-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-except-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | raise Exception('yarr!') 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertTrue(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/exceptions/try-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | 3 | try: 4 | pass 5 | finally: 6 | hit_finally = True 7 | 8 | ___assertTrue(hit_finally) 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/iter/iter-comprehensions.py: -------------------------------------------------------------------------------- 1 | # Test result of triple loop (too big to inline) 2 | TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), 3 | (0, 1, 0), (0, 1, 1), (0, 1, 2), 4 | (0, 2, 0), (0, 2, 1), (0, 2, 2), 5 | 6 | (1, 0, 0), (1, 0, 1), (1, 0, 2), 7 | (1, 1, 0), (1, 1, 1), (1, 1, 2), 8 | (1, 2, 0), (1, 2, 1), (1, 2, 2), 9 | 10 | (2, 0, 0), (2, 0, 1), (2, 0, 2), 11 | (2, 1, 0), (2, 1, 1), (2, 1, 2), 12 | (2, 2, 0), (2, 2, 1), (2, 2, 2)] 13 | 14 | 15 | seq = range(3) 16 | res = [] 17 | for i in iter(seq): 18 | for j in iter(seq): 19 | for k in iter(seq): 20 | res.append((i, j, k)) 21 | ___assertEqual(res, TRIPLETS) 22 | 23 | seq = range(3) 24 | res = [(i, j, k) for i in seq for j in seq for k in seq] 25 | ___assertEqual(res, TRIPLETS) 26 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/iter/iter-misc.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | 20 | check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10))) 21 | check_for_loop(iter(range(10)), list(range(10))) 22 | check_for_loop(iter("abcde"), ["a", "b", "c", "d", "e"]) 23 | 24 | dict = {} 25 | for i in range(10): 26 | dict[i] = None 27 | check_for_loop(dict, list(dict.keys())) 28 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/iter/iter-simple.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | # Test basic use of iter() function 20 | check_iterator(iter(range(10)), list(range(10))) 21 | 22 | # Test that iter(iter(x)) is the same as iter(x) 23 | seq = list(range(10)) 24 | it = iter(seq) 25 | it2 = iter(it) 26 | ___assertTrue(it is it2) 27 | 28 | check_for_loop(iter(range(10)), list(range(10))) 29 | 30 | check_for_loop(iter([]), []) 31 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/iter/iter-stop.py: -------------------------------------------------------------------------------- 1 | # test_sinkstate_list 2 | # This used to fail 3 | a = list(range(5)) 4 | b = iter(a) 5 | ___assertEqual(list(b), list(range(5))) 6 | a.extend(range(5, 10)) 7 | ___assertEqual(list(b), []) 8 | 9 | # test_sinkstate_tuple 10 | a = (0, 1, 2, 3, 4) 11 | b = iter(a) 12 | ___assertEqual(list(b), list(range(5))) 13 | ___assertEqual(list(b), []) 14 | 15 | # test_sinkstate_string 16 | a = "abcde" 17 | b = iter(a) 18 | ___assertEqual(list(b), ['a', 'b', 'c', 'd', 'e']) 19 | ___assertEqual(list(b), []) 20 | 21 | # test_sinkstate_callable 22 | # This used to fail 23 | def spam(state=[0]): 24 | i = state[0] 25 | state[0] = i+1 26 | if i == 10: 27 | raise AssertionError("shouldn't have gotten this far") 28 | return i 29 | b = iter(spam, 5) 30 | ___assertEqual(list(b), list(range(5))) 31 | ___assertEqual(list(b), []) 32 | 33 | # test_sinkstate_dict 34 | # XXX For a more thorough test, see towards the end of: 35 | # http://mail.python.org/pipermail/python-dev/2002-July/026512.html 36 | a = {1:1, 2:2, 0:0, 4:4, 3:3} 37 | for b in iter(a), a.keys(), a.items(), a.values(): 38 | b = iter(a) 39 | ___assertEqual(len(list(b)), 5) 40 | ___assertEqual(list(b), []) 41 | 42 | # test_sinkstate_range 43 | a = range(5) 44 | b = iter(a) 45 | ___assertEqual(list(b), list(range(5))) 46 | ___assertEqual(list(b), []) 47 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/lists/test_list_identity.py: -------------------------------------------------------------------------------- 1 | if(not ([] is not [])): raise Exception('list identity') 2 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/lists/test_list_simple.py: -------------------------------------------------------------------------------- 1 | if (not (list([]) == [])): raise Exception('List empty') 2 | l0_3 = [0, 1, 2, 3] 3 | l0_3_bis = list(l0_3) 4 | if (not (l0_3 == l0_3_bis)): raise Exception('List identity') 5 | if (not (l0_3 is not l0_3_bis)): raise Exception('List identity') 6 | if (not (list(()) == [])): raise Exception( 'List tuple') 7 | if (not (list((0, 1, 2, 3)), [0, 1, 2, 3])): raise Exception('List tuple 2') 8 | if (not (list('') == [])): raise Exception( 'List string 1') 9 | if (not (list('spam') == ['s', 'p', 'a', 'm'])): raise Exception( 'List string 2') 10 | 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/lists/test_list_truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not []) 2 | ___assertTrue([42]) 3 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/range/range-errs.py: -------------------------------------------------------------------------------- 1 | ___assertRaises(TypeError, range) 2 | ___assertRaises(TypeError, range, 1, 2, 3, 4) 3 | ___assertRaises(ValueError, range, 1, 2, 0) 4 | 5 | ___assertRaises(TypeError, range, 0.0, 2, 1) 6 | ___assertRaises(TypeError, range, 1, 2.0, 1) 7 | ___assertRaises(TypeError, range, 1, 2, 1.0) 8 | ___assertRaises(TypeError, range, 1e100, 1e101, 1e101) 9 | 10 | ___assertRaises(TypeError, range, 0, "spam") 11 | ___assertRaises(TypeError, range, 0, 42, "spam") 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/range/range-list.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(range(3)), [0, 1, 2]) 2 | ___assertEqual(list(range(1, 5)), [1, 2, 3, 4]) 3 | ___assertEqual(list(range(0)), []) 4 | ___assertEqual(list(range(-3)), []) 5 | ___assertEqual(list(range(1, 10, 3)), [1, 4, 7]) 6 | ___assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/range/range-vars.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | b = 100 3 | c = 50 4 | 5 | ___assertEqual(list(range(a, a+2)), [a, a+1]) 6 | ___assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) 7 | ___assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) 8 | 9 | seq = list(range(a, b, c)) 10 | ___assertIn(a, seq) 11 | ___assertNotIn(b, seq) 12 | ___assertEqual(len(seq), 2) 13 | 14 | seq = list(range(b, a, -c)) 15 | ___assertIn(b, seq) 16 | ___assertNotIn(a, seq) 17 | ___assertEqual(len(seq), 2) 18 | 19 | seq = list(range(-a, -b, -c)) 20 | ___assertIn(-a, seq) 21 | ___assertNotIn(-b, seq) 22 | ___assertEqual(len(seq), 2) 23 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/bound-and-free.py: -------------------------------------------------------------------------------- 1 | # var is bound and free in class 2 | 3 | def f(x): 4 | class C: 5 | def m(self): 6 | return x 7 | a = x 8 | return C 9 | 10 | inst = f(3)() 11 | ___assertEqual(inst.a, inst.m()) 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/extra-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder2(x): 2 | def extra(): # check freevars passing through non-use scopes 3 | def adder(y): 4 | return x + y 5 | return adder 6 | return extra() 7 | 8 | inc = make_adder2(1) 9 | plus10 = make_adder2(10) 10 | 11 | ___assertEqual(inc(1), 2) 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/freevar-in-method.py: -------------------------------------------------------------------------------- 1 | def test(): 2 | method_and_var = "var" 3 | class Test: 4 | def method_and_var(self): 5 | return "method" 6 | def test(self): 7 | return method_and_var 8 | def actual_global(self): 9 | return str("global") 10 | def str(self): 11 | return str(self) 12 | return Test() 13 | 14 | t = test() 15 | ___assertEqual(t.test(), "var") 16 | ___assertEqual(t.method_and_var(), "method") 17 | ___assertEqual(t.actual_global(), "global") 18 | 19 | method_and_var = "var" 20 | class Test: 21 | # this class is not nested, so the rules are different 22 | def method_and_var(self): 23 | return "method" 24 | def test(self): 25 | return method_and_var 26 | def actual_global(self): 27 | return str("global") 28 | def str(self): 29 | return str(self) 30 | 31 | t = Test() 32 | ___assertEqual(t.test(), "var") 33 | ___assertEqual(t.method_and_var(), "method") 34 | ___assertEqual(t.actual_global(), "global") 35 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/lambda1.py: -------------------------------------------------------------------------------- 1 | f1 = lambda x: lambda y: x + y 2 | inc = f1(1) 3 | plus10 = f1(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/lambda2.py: -------------------------------------------------------------------------------- 1 | f2 = lambda x: (lambda : lambda y: x + y)() 2 | inc = f2(1) 3 | plus10 = f2(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/lambda3.py: -------------------------------------------------------------------------------- 1 | f3 = lambda x: lambda y: global_x + y 2 | global_x = 1 3 | inc = f3(None) 4 | ___assertEqual(inc(2), 3) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/lambda4.py: -------------------------------------------------------------------------------- 1 | f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) 2 | g = f8(1, 2, 3) 3 | h = g(2, 4, 6) 4 | ___assertEqual(h(), 18) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/locals-class.py: -------------------------------------------------------------------------------- 1 | # This test verifies that calling locals() does not pollute 2 | # the local namespace of the class with free variables. Old 3 | # versions of Python had a bug, where a free variable being 4 | # passed through a class namespace would be inserted into 5 | # locals() by locals() or exec or a trace function. 6 | # 7 | # The real bug lies in frame code that copies variables 8 | # between fast locals and the locals dict, e.g. when executing 9 | # a trace function. 10 | 11 | def f(x): 12 | class C: 13 | x = 12 14 | def m(self): 15 | return x 16 | locals() 17 | return C 18 | 19 | ___assertEqual(f(1).x, 12) 20 | 21 | def f(x): 22 | class C: 23 | y = x 24 | def m(self): 25 | return x 26 | z = list(locals()) 27 | return C 28 | 29 | varnames = f(1).z 30 | ___assertNotIn("x", varnames) 31 | ___assertIn("y", varnames) 32 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/locals-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | def h(z): 4 | return y + z 5 | w = x + y 6 | y += 3 7 | return locals() 8 | return g 9 | 10 | d = f(2)(4) 11 | ___assertIn('h', d) 12 | del d['h'] 13 | ___assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) 14 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/mixed-freevars-and-cellvars.py: -------------------------------------------------------------------------------- 1 | def identity(x): 2 | return x 3 | 4 | def f(x, y, z): 5 | def g(a, b, c): 6 | a = a + x # 3 7 | def h(): 8 | # z * (4 + 9) 9 | # 3 * 13 10 | return identity(z * (b + y)) 11 | y = c + z # 9 12 | return h 13 | return g 14 | 15 | g = f(1, 2, 3) 16 | h = g(2, 4, 6) 17 | ___assertEqual(h(), 39) 18 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nearest-enclosing-scope.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | x = 42 # check that this masks binding in f() 4 | def h(z): 5 | return x + z 6 | return h 7 | return g(2) 8 | 9 | test_func = f(10) 10 | ___assertEqual(test_func(5), 47) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nested-nonlocal.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(): 3 | nonlocal x 4 | x -= 2 5 | def h(): 6 | nonlocal x 7 | x += 4 8 | return x 9 | return h 10 | return g 11 | 12 | g = f(1) 13 | h = g() 14 | ___assertEqual(h(), 3) 15 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nesting-global-no-free.py: -------------------------------------------------------------------------------- 1 | def make_adder4(): # XXX add exta level of indirection 2 | def nest(): 3 | def nest(): 4 | def adder(y): 5 | return global_x + y # check that plain old globals work 6 | return adder 7 | return nest() 8 | return nest() 9 | 10 | global_x = 1 11 | adder = make_adder4() 12 | ___assertEqual(adder(1), 2) 13 | 14 | global_x = 10 15 | ___assertEqual(adder(-2), 8) 16 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nesting-plus-free-ref-to-global.py: -------------------------------------------------------------------------------- 1 | def make_adder6(x): 2 | global global_nest_x 3 | def adder(y): 4 | return global_nest_x + y 5 | global_nest_x = x 6 | return adder 7 | 8 | inc = make_adder6(1) 9 | plus10 = make_adder6(10) 10 | 11 | ___assertEqual(inc(1), 11) # there's only one global 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nesting-through-class.py: -------------------------------------------------------------------------------- 1 | def make_adder5(x): 2 | class Adder: 3 | def __call__(self, y): 4 | return x + y 5 | return Adder() 6 | 7 | inc = make_adder5(1) 8 | plus10 = make_adder5(10) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nonlocal-class.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | nonlocal x 4 | x += 1 5 | def get(self): 6 | return x 7 | return c() 8 | 9 | c = f(0) 10 | ___assertEqual(c.get(), 1) 11 | ___assertNotIn("x", c.__class__.__dict__) 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nonlocal-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def inc(): 3 | nonlocal x 4 | x += 1 5 | return x 6 | def dec(): 7 | nonlocal x 8 | x -= 1 9 | return x 10 | return inc, dec 11 | 12 | inc, dec = f(0) 13 | ___assertEqual(inc(), 1) 14 | ___assertEqual(inc(), 2) 15 | ___assertEqual(dec(), 1) 16 | ___assertEqual(dec(), 0) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/nonlocal-method.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | def inc(self): 4 | nonlocal x 5 | x += 1 6 | return x 7 | def dec(self): 8 | nonlocal x 9 | x -= 1 10 | return x 11 | return c() 12 | c = f(0) 13 | ___assertEqual(c.inc(), 1) 14 | ___assertEqual(c.inc(), 2) 15 | ___assertEqual(c.dec(), 1) 16 | ___assertEqual(c.dec(), 0) 17 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/recursion.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def fact(n): 3 | if n == 0: 4 | return 1 5 | else: 6 | return n * fact(n - 1) 7 | if x >= 0: 8 | return fact(x) 9 | else: 10 | raise ValueError("x must be >= 0") 11 | 12 | ___assertEqual(f(6), 720) 13 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/simple-and-rebinding.py: -------------------------------------------------------------------------------- 1 | def make_adder3(x): 2 | def adder(y): 3 | return x + y 4 | x = x + 1 # check tracking of assignment to x in defining scope 5 | return adder 6 | 7 | inc = make_adder3(0) 8 | plus10 = make_adder3(9) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/simple-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder(x): 2 | def adder(y): 3 | return x + y 4 | return adder 5 | 6 | inc = make_adder(1) 7 | plus10 = make_adder(10) 8 | 9 | ___assertEqual(inc(1), 2) 10 | ___assertEqual(plus10(-2), 8) 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/scope/unbound-local.py: -------------------------------------------------------------------------------- 1 | def errorInOuter(): 2 | print(y) 3 | def inner(): 4 | return y 5 | y = 1 6 | 7 | def errorInInner(): 8 | def inner(): 9 | return y 10 | inner() 11 | y = 1 12 | 13 | ___assertRaises(UnboundLocalError, errorInOuter) 14 | ___assertRaises(NameError, errorInInner) 15 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/tuple/tuple-add.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u += (2, 3) 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/tuple/tuple-constructors.py: -------------------------------------------------------------------------------- 1 | # calling built-in types without argument must return empty 2 | ___assertEqual(tuple(), ()) 3 | t0_3 = (0, 1, 2, 3) 4 | t0_3_bis = tuple(t0_3) 5 | ___assertTrue(t0_3 is t0_3_bis) 6 | ___assertEqual(tuple([]), ()) 7 | ___assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) 8 | ___assertEqual(tuple(''), ()) 9 | ___assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) 10 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/tuple/tuple-length.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len(()), 0) 2 | ___assertEqual(len((0,)), 1) 3 | ___assertEqual(len((0, 1, 2)), 3) 4 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/tuple/tuple-mul.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u *= 3 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/tuple/tuple-truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not ()) 2 | ___assertTrue((42, )) 3 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_booleans.py: -------------------------------------------------------------------------------- 1 | if 0 or 0: raise Exception('0 or 0 is true instead of false') 2 | if 1 and 1: pass 3 | else: raise Exception('1 and 1 is false instead of true') 4 | if not 1: raise Exception('not 1 is true instead of false') 5 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_comparisons.py: -------------------------------------------------------------------------------- 1 | if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass 2 | else: raise Exception('int comparisons failed') 3 | if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass 4 | else: raise Exception('float comparisons failed') 5 | if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass 6 | else: raise Exception('string comparisons failed') 7 | if None is None: pass 8 | else: raise Exception('identity test failed') 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_div_zero.py: -------------------------------------------------------------------------------- 1 | try: 5.0 / 0.0 2 | except ZeroDivisionError: pass 3 | else: raise Exception("5.0 / 0.0 didn't raise ZeroDivisionError") 4 | 5 | try: 5.0 // 0.0 6 | except ZeroDivisionError: pass 7 | else: raise Exception("5.0 // 0.0 didn't raise ZeroDivisionError") 8 | 9 | try: 5.0 % 0.0 10 | except ZeroDivisionError: pass 11 | else: raise Exception("5.0 % 0.0 didn't raise ZeroDivisionError") 12 | 13 | try: 5 / 0 14 | except ZeroDivisionError: pass 15 | else: raise Exception("5 / 0 didn't raise ZeroDivisionError") 16 | 17 | try: 5 // 0 18 | except ZeroDivisionError: pass 19 | else: raise Exception("5 // 0 didn't raise ZeroDivisionError") 20 | 21 | try: 5 % 0 22 | except ZeroDivisionError: pass 23 | else: raise Exception("5 % 0 didn't raise ZeroDivisionError") 24 | 25 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_floats.py: -------------------------------------------------------------------------------- 1 | if 12.0 + 24.0 != 36.0: raise Exception('float op +') 2 | if 12.0 + (-24.0) != -12.0: raise Exception('float op +/-') 3 | if (-12.0) + 24.0 != 12.0: raise Exception('float op -/+') 4 | if (-12.0) + (-24.0) != -36.0: raise Exception('float op -/+/-') 5 | if not 12.0 < 24.0: raise Exception('float op <') 6 | if not -24.0 < -12.0: raise Exception('float op < negative') 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_simple_string_ops.py: -------------------------------------------------------------------------------- 1 | if 'xyz' + 'abcde' != 'xyzabcde': raise Exception('string concatenation') 2 | if 'xyz'*3 != 'xyzxyzxyz': raise Exception('string repetition *3') 3 | if 0*'abcde' != '': raise Exception('string repetition 0*') 4 | if min('abc') != 'a' or max('abc') != 'c': raise Exception('min/max string') 5 | if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass 6 | else: raise Exception('in/not in string') 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_simple_strings.py: -------------------------------------------------------------------------------- 1 | if len('') != 0: raise Exception('len(\'\')') 2 | if len('a') != 1: raise Exception('len(\'a\')') 3 | if len('abcdef') != 6: raise Exception('len(\'abcdef\')') 4 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/test_string_slices.py: -------------------------------------------------------------------------------- 1 | a = '0123456789' 2 | if (not (a[::] == a)): raise Exception('Slice total') 3 | if (not (a[::2] == '02468')): raise Exception('Slice 2') 4 | if (not (a[1::2] == '13579')): raise Exception('Slice 1::2') 5 | if (not (a[::-1] =='9876543210')): raise Exception('Slice ::-1') 6 | if (not (a[::-2] == '97531')): raise Exception('Slice ::-2') 7 | if (not (a[3::-2] == '31')): raise Exception('Slice 3::-2') 8 | if (not (a[-100:100:] == a)): raise Exception('Slice -100::100') 9 | if (not (a[100:-100:-1] == a[::-1])): raise Exception('Slice triple') 10 | if (not (a[-100:100:2] == '02468')): raise Exception('Slice triple 2') 11 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/types_truthy1.py: -------------------------------------------------------------------------------- 1 | if None: raise Exception('None is true instead of false') 2 | if 0: raise Exception('0 is true instead of false') 3 | if 0.0: raise Exception('0.0 is true instead of false') 4 | if '': raise Exception('\'\' is true instead of false') 5 | if not 1: raise Exception('1 is false instead of true') 6 | if not 1.0: raise Exception('1.0 is false instead of true') 7 | if not 'x': raise Exception('\'x\' is false instead of true') 8 | if not {'x': 1}: raise Exception('{\'x\': 1} is false instead of true') 9 | -------------------------------------------------------------------------------- /design3/cs173-python/python-reference/types/types_truthy2.py: -------------------------------------------------------------------------------- 1 | def f(): pass 2 | class C: pass 3 | x = C() 4 | if not f: raise Exception('f is false instead of true') 5 | if not C: raise Exception('C is false instead of true') 6 | if not x: raise Exception('x is false instead of true') 7 | -------------------------------------------------------------------------------- /design3/cs173-python/python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (define-type PyExp 4 | [PyNum (n : number)] 5 | [PyTuple (l : (listof PyExp))] 6 | [PySeq (es : (listof PyExp))] 7 | [PyId (x : symbol)] 8 | [PySet! (id : symbol) (value : PyExp)] 9 | [PyApp (fun : PyExp) (args : (listof PyExp)) (starargs : PyExp)] 10 | [PyFunc (args : (listof symbol)) (vararg : (optionof symbol)) (body : PyExp)] 11 | [PyReturn (value : PyExp)] 12 | [PyIf (test : PyExp) (then : PyExp) (else : PyExp)] 13 | [PyOp (id : symbol) (args : (listof PyExp))] 14 | [PyPass]) 15 | 16 | (define someF some) 17 | (define noneF none) 18 | 19 | -------------------------------------------------------------------------------- /design4/cs173-python/.gitignore: -------------------------------------------------------------------------------- 1 | compiled/ 2 | *.swp 3 | *~ 4 | -------------------------------------------------------------------------------- /design4/cs173-python/parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /design4/cs173-python/py-prelude.py: -------------------------------------------------------------------------------- 1 | def ___assertEqual(l, r): 2 | assert(l == r) 3 | 4 | def ___assertNotEqual(l, r): 5 | assert(not (l == r)) 6 | 7 | def ___assertTrue(v): 8 | assert(v) 9 | 10 | def ___assertFalse(v): 11 | assert(not v) 12 | 13 | def ___assertIs(l, r): 14 | assert(l is r) 15 | 16 | def ___assertIsNot(l, r): 17 | assert(not (l is r)) 18 | 19 | def ___assertIn(l, r): 20 | assert(l in r) 21 | 22 | def ___assertNotIn(l, r): 23 | assert(not (l in r)) 24 | 25 | def ___assertRaises(e, f, *args): 26 | try: 27 | f(*args) 28 | except e as the_exn: 29 | return 30 | else: 31 | assert(False) 32 | assert(False) 33 | 34 | def ___fail(): 35 | assert(False) 36 | -------------------------------------------------------------------------------- /design4/cs173-python/python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | elif t in [bytes]: return {'nodetype': 'Bytes', 'value': str(v)} 22 | else: 23 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 24 | % v) 25 | 26 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 27 | n_dict['nodetype'] = n.__class__.__name__ 28 | return n_dict 29 | 30 | if __name__ == '__main__': 31 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 32 | 33 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-callable.py: -------------------------------------------------------------------------------- 1 | ___assertIs(callable(len), True) 2 | ___assertIs(callable(1), False) 3 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-compare-list-dict.py: -------------------------------------------------------------------------------- 1 | x = [1] 2 | ___assertIs(x is x, True) 3 | ___assertIs(x is not x, False) 4 | 5 | ___assertIs(1 in x, True) 6 | ___assertIs(0 in x, False) 7 | ___assertIs(1 not in x, False) 8 | ___assertIs(0 not in x, True) 9 | 10 | x = {1: 2} 11 | ___assertIs(x is x, True) 12 | ___assertIs(x is not x, False) 13 | 14 | ___assertIs(1 in x, True) 15 | ___assertIs(0 in x, False) 16 | ___assertIs(1 not in x, False) 17 | ___assertIs(0 not in x, True) 18 | 19 | ___assertIs(not True, False) 20 | ___assertIs(not False, True) 21 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-compare.py: -------------------------------------------------------------------------------- 1 | ___assertIs(1==1, True) 2 | ___assertIs(1==0, False) 3 | ___assertIs(0<1, True) 4 | ___assertIs(1<0, False) 5 | ___assertIs(0<=0, True) 6 | ___assertIs(1<=0, False) 7 | ___assertIs(1>0, True) 8 | ___assertIs(1>1, False) 9 | ___assertIs(1>=1, True) 10 | ___assertIs(0>=1, False) 11 | ___assertIs(0!=1, True) 12 | ___assertIs(0!=0, False) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-convert.py: -------------------------------------------------------------------------------- 1 | ___assertIs(bool(10), True) 2 | ___assertIs(bool(1), True) 3 | ___assertIs(bool(-1), True) 4 | ___assertIs(bool(0), False) 5 | ___assertIs(bool("hello"), True) 6 | ___assertIs(bool(""), False) 7 | ___assertIs(bool(), False) 8 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-float.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(float(False), 0.0) 2 | ___assertIsNot(float(False), False) 3 | ___assertEqual(float(True), 1.0) 4 | ___assertIsNot(float(True), True) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-int.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(int(False), 0) 2 | ___assertIsNot(int(False), False) 3 | ___assertEqual(int(True), 1) 4 | ___assertIsNot(int(True), True) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-isinstance.py: -------------------------------------------------------------------------------- 1 | ___assertIs(isinstance(True, bool), True) 2 | ___assertIs(isinstance(False, bool), True) 3 | ___assertIs(isinstance(True, int), True) 4 | ___assertIs(isinstance(False, int), True) 5 | ___assertIs(isinstance(1, bool), False) 6 | ___assertIs(isinstance(0, bool), False) 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-math.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(+False, 0) 2 | ___assertIsNot(+False, False) 3 | ___assertEqual(-False, 0) 4 | ___assertIsNot(-False, False) 5 | ___assertEqual(abs(False), 0) 6 | ___assertIsNot(abs(False), False) 7 | ___assertEqual(+True, 1) 8 | ___assertIsNot(+True, True) 9 | ___assertEqual(-True, -1) 10 | ___assertEqual(abs(True), 1) 11 | ___assertIsNot(abs(True), True) 12 | ___assertEqual(~False, -1) 13 | ___assertEqual(~True, -2) 14 | 15 | ___assertEqual(False+2, 2) 16 | ___assertEqual(True+2, 3) 17 | ___assertEqual(2+False, 2) 18 | ___assertEqual(2+True, 3) 19 | 20 | ___assertEqual(False+False, 0) 21 | ___assertIsNot(False+False, False) 22 | ___assertEqual(False+True, 1) 23 | ___assertIsNot(False+True, True) 24 | ___assertEqual(True+False, 1) 25 | ___assertIsNot(True+False, True) 26 | ___assertEqual(True+True, 2) 27 | 28 | ___assertEqual(True-True, 0) 29 | ___assertIsNot(True-True, False) 30 | ___assertEqual(False-False, 0) 31 | ___assertIsNot(False-False, False) 32 | ___assertEqual(True-False, 1) 33 | ___assertIsNot(True-False, True) 34 | ___assertEqual(False-True, -1) 35 | 36 | ___assertEqual(True*1, 1) 37 | ___assertEqual(False*1, 0) 38 | ___assertIsNot(False*1, False) 39 | 40 | ___assertEqual(True/1, 1) 41 | ___assertIsNot(True/1, True) 42 | ___assertEqual(False/1, 0) 43 | ___assertIsNot(False/1, False) 44 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/bool/bool-str.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(str(False), 'False') 2 | ___assertEqual(str(True), 'True') 3 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/all.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(all([2, 4, 6]), True) 2 | ___assertEqual(all([2, None, 6]), False) 3 | ___assertRaises(TypeError, all, 10) # Non-iterable 4 | ___assertRaises(TypeError, all) # No args 5 | ___assertRaises(TypeError, all, [2, 4, 6], []) # Too many args 6 | ___assertEqual(all([]), True) # Empty iterator 7 | S = [50, 60] 8 | ___assertEqual(all(x > 42 for x in S), True) 9 | S = [50, 40, 60] 10 | ___assertEqual(all(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/any.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(any([None, None, None]), False) 2 | ___assertEqual(any([None, 4, None]), True) 3 | ___assertRaises(TypeError, any, 10) # Non-iterable 4 | ___assertRaises(TypeError, any) # No args 5 | ___assertRaises(TypeError, any, [2, 4, 6], []) # Too many args 6 | ___assertEqual(any([]), False) # Empty iterator 7 | S = [40, 60, 30] 8 | ___assertEqual(any(x > 42 for x in S), True) 9 | S = [10, 20, 30] 10 | ___assertEqual(any(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/callable.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(callable(len)) 2 | ___assertFalse(callable("a")) 3 | ___assertTrue(callable(callable)) 4 | ___assertTrue(callable(lambda x, y: x + y)) 5 | 6 | def f(): pass 7 | ___assertTrue(callable(f)) 8 | 9 | class C1: 10 | def meth(self): pass 11 | ___assertTrue(callable(C1)) 12 | c = C1() 13 | ___assertTrue(callable(c.meth)) 14 | ___assertFalse(callable(c)) 15 | 16 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/filter.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) 2 | ___assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) 3 | ___assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) 4 | def badfunc(): 5 | pass 6 | ___assertRaises(TypeError, list, filter(badfunc, range(5))) 7 | 8 | # test bltinmodule.c::filtertuple() 9 | ___assertEqual(list(filter(None, (1, 2))), [1, 2]) 10 | ___assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) 11 | ___assertRaises(TypeError, list, filter(42, (1, 2))) 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/isinstance.py: -------------------------------------------------------------------------------- 1 | class C: 2 | pass 3 | class D(C): 4 | pass 5 | class E: 6 | pass 7 | c = C() 8 | d = D() 9 | e = E() 10 | ___assertTrue(isinstance(c, C)) 11 | ___assertTrue(isinstance(d, C)) 12 | ___assertTrue(not isinstance(e, C)) 13 | ___assertTrue(not isinstance(c, D)) 14 | ___assertTrue(not isinstance('foo', E)) 15 | ___assertRaises(TypeError, isinstance, E, 'foo') 16 | ___assertRaises(TypeError, isinstance) 17 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/builtin/len.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len('123'), 3) 2 | ___assertEqual(len(()), 0) 3 | ___assertEqual(len((1, 2, 3, 4)), 4) 4 | ___assertEqual(len([1, 2, 3, 4]), 4) 5 | ___assertEqual(len({}), 0) 6 | ___assertEqual(len({'a':1, 'b': 2}), 2) 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-bool.py: -------------------------------------------------------------------------------- 1 | ___assertIs(not {}, True) 2 | ___assertTrue({1: 2}) 3 | ___assertIs(bool({}), False) 4 | ___assertIs(bool({1: 2}), True) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-clear.py: -------------------------------------------------------------------------------- 1 | d = {1:1, 2:2, 3:3} 2 | d.clear() 3 | ___assertEqual(d, {}) 4 | 5 | ___assertRaises(TypeError, d.clear, None) 6 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-contains.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertNotIn('a', d) 3 | ___assertFalse('a' in d) 4 | ___assertTrue('a' not in d) 5 | d = {'a': 1, 'b': 2} 6 | ___assertIn('a', d) 7 | ___assertIn('b', d) 8 | ___assertNotIn('c', d) 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-get.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertIs(d.get('c'), None) 3 | ___assertEqual(d.get('c', 3), 3) 4 | d = {'a': 1, 'b': 2} 5 | ___assertIs(d.get('c'), None) 6 | ___assertEqual(d.get('c', 3), 3) 7 | ___assertEqual(d.get('a'), 1) 8 | ___assertEqual(d.get('a', 3), 1) 9 | ___assertRaises(TypeError, d.get) 10 | ___assertRaises(TypeError, d.get, None, None, None) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-getitem.py: -------------------------------------------------------------------------------- 1 | d = {'a': 1, 'b': 2} 2 | ___assertEqual(d['a'], 1) 3 | ___assertEqual(d['b'], 2) 4 | d['c'] = 3 5 | d['a'] = 4 6 | ___assertEqual(d['c'], 3) 7 | ___assertEqual(d['a'], 4) 8 | del d['b'] 9 | ___assertEqual(d, {'a': 4, 'c': 3}) 10 | 11 | ___assertRaises(TypeError, d.__getitem__) 12 | 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-items.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.items()), set()) 3 | 4 | d = {1:2} 5 | ___assertEqual(set(d.items()), {(1, 2)}) 6 | ___assertRaises(TypeError, d.items, None) 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-keys.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.keys()), set()) 3 | d = {'a': 1, 'b': 2} 4 | k = d.keys() 5 | ___assertIn('a', d) 6 | ___assertIn('b', d) 7 | ___assertRaises(TypeError, d.keys, None) 8 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-set-keys.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.keys() 2 | k2 = {1:1, 2:2, 3:3}.keys() 3 | k3 = {4:4}.keys() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {1,2}) 7 | ___assertEqual(k2 - k1, {3}) 8 | ___assertEqual(k3 - k1, {4}) 9 | ___assertEqual(k1 & k2, {1,2}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {1,2,3}) 12 | ___assertEqual(k1 ^ k2, {3}) 13 | ___assertEqual(k1 ^ k3, {1,2,4}) 14 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-update.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | d.update({1:100}) 3 | d.update({2:20}) 4 | d.update({1:1, 2:2, 3:3}) 5 | ___assertEqual(d, {1:1, 2:2, 3:3}) 6 | 7 | d.update() 8 | ___assertEqual(d, {1:1, 2:2, 3:3}) 9 | 10 | ___assertRaises((TypeError, AttributeError), d.update, None) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-values-set.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.items() 2 | k2 = {1:1, 2:2, 3:3}.items() 3 | k3 = {4:4}.items() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {(1,1), (2,2)}) 7 | ___assertEqual(k2 - k1, {(3,3)}) 8 | ___assertEqual(k3 - k1, {(4,4)}) 9 | ___assertEqual(k1 & k2, {(1,1), (2,2)}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) 12 | ___assertEqual(k1 ^ k2, {(3,3)}) 13 | ___assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) 14 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/dict/dict-values.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.values()), set()) 3 | d = {1:2} 4 | ___assertEqual(set(d.values()), {2}) 5 | ___assertRaises(TypeError, d.values, None) 6 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/except-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | except KeyError: 8 | pass 9 | raise 10 | ___assertRaises(TypeError, reraise) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/invalid-reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise 3 | except RuntimeError as e: 4 | ___assertIn("No active exception", str(e)) 5 | else: 6 | ___fail("No exception raised") 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/nested-else.py: -------------------------------------------------------------------------------- 1 | hit_else = False 2 | hit_finally = False 3 | hit_except = False 4 | hit_inner_except = False 5 | hit_inner_else = False 6 | 7 | try: 8 | try: 9 | pass 10 | except: 11 | hit_inner_except = True 12 | else: 13 | hit_inner_else = True 14 | 15 | raise Exception('outer exception') 16 | except: 17 | hit_except = True 18 | else: 19 | hit_else = True 20 | finally: 21 | hit_finally = True 22 | 23 | ___assertFalse(hit_inner_except) 24 | ___assertTrue(hit_inner_else) 25 | ___assertFalse(hit_else) 26 | ___assertTrue(hit_finally) 27 | ___assertTrue(hit_except) 28 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/nested-reraise.py: -------------------------------------------------------------------------------- 1 | def nested_reraise(): 2 | raise 3 | def reraise(): 4 | try: 5 | raise TypeError("foo") 6 | except: 7 | nested_reraise() 8 | ___assertRaises(TypeError, reraise) 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/nested.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | hit_inner_except = False 3 | hit_inner_finally = False 4 | 5 | try: 6 | try: 7 | raise Exception('inner exception') 8 | except: 9 | hit_inner_except = True 10 | finally: 11 | hit_inner_finally = True 12 | finally: 13 | hit_finally = True 14 | 15 | ___assertTrue(hit_inner_except) 16 | ___assertTrue(hit_inner_finally) 17 | ___assertTrue(hit_finally) 18 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | try: 3 | raise IndexError() 4 | except IndexError as e: 5 | exc1 = e 6 | raise 7 | except IndexError as exc2: 8 | ___assertTrue(exc1 is exc2) 9 | else: 10 | ___fail("No exception raised") 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/test-finally-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | finally: 8 | raise 9 | ___assertRaises(KeyError, reraise) 10 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/test-try-except-else.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | raise Exception('foo!') 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_else) 12 | ___assertTrue(hit_except) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/test-try-except-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | pass 5 | except: 6 | hit_except = True 7 | 8 | ___assertFalse(hit_except) 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/test-try-except.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | raise Exception('ahoy!') 5 | except: 6 | hit_except = True 7 | 8 | ___assertTrue(hit_except) 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-except-else-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | pass 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertFalse(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertTrue(hit_else) 17 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-except-else-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | raise Exception('nyaa!') 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertTrue(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertFalse(hit_else) 17 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-except-else-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_else) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-except-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-except-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | raise Exception('yarr!') 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertTrue(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/exceptions/try-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | 3 | try: 4 | pass 5 | finally: 6 | hit_finally = True 7 | 8 | ___assertTrue(hit_finally) 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/iter/iter-comprehensions.py: -------------------------------------------------------------------------------- 1 | # Test result of triple loop (too big to inline) 2 | TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), 3 | (0, 1, 0), (0, 1, 1), (0, 1, 2), 4 | (0, 2, 0), (0, 2, 1), (0, 2, 2), 5 | 6 | (1, 0, 0), (1, 0, 1), (1, 0, 2), 7 | (1, 1, 0), (1, 1, 1), (1, 1, 2), 8 | (1, 2, 0), (1, 2, 1), (1, 2, 2), 9 | 10 | (2, 0, 0), (2, 0, 1), (2, 0, 2), 11 | (2, 1, 0), (2, 1, 1), (2, 1, 2), 12 | (2, 2, 0), (2, 2, 1), (2, 2, 2)] 13 | 14 | 15 | seq = range(3) 16 | res = [] 17 | for i in iter(seq): 18 | for j in iter(seq): 19 | for k in iter(seq): 20 | res.append((i, j, k)) 21 | ___assertEqual(res, TRIPLETS) 22 | 23 | seq = range(3) 24 | res = [(i, j, k) for i in seq for j in seq for k in seq] 25 | ___assertEqual(res, TRIPLETS) 26 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/iter/iter-misc.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | 20 | check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10))) 21 | check_for_loop(iter(range(10)), list(range(10))) 22 | check_for_loop(iter("abcde"), ["a", "b", "c", "d", "e"]) 23 | 24 | dict = {} 25 | for i in range(10): 26 | dict[i] = None 27 | check_for_loop(dict, list(dict.keys())) 28 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/iter/iter-simple.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | # Test basic use of iter() function 20 | check_iterator(iter(range(10)), list(range(10))) 21 | 22 | # Test that iter(iter(x)) is the same as iter(x) 23 | seq = list(range(10)) 24 | it = iter(seq) 25 | it2 = iter(it) 26 | ___assertTrue(it is it2) 27 | 28 | check_for_loop(iter(range(10)), list(range(10))) 29 | 30 | check_for_loop(iter([]), []) 31 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/iter/iter-stop.py: -------------------------------------------------------------------------------- 1 | # test_sinkstate_list 2 | # This used to fail 3 | a = list(range(5)) 4 | b = iter(a) 5 | ___assertEqual(list(b), list(range(5))) 6 | a.extend(range(5, 10)) 7 | ___assertEqual(list(b), []) 8 | 9 | # test_sinkstate_tuple 10 | a = (0, 1, 2, 3, 4) 11 | b = iter(a) 12 | ___assertEqual(list(b), list(range(5))) 13 | ___assertEqual(list(b), []) 14 | 15 | # test_sinkstate_string 16 | a = "abcde" 17 | b = iter(a) 18 | ___assertEqual(list(b), ['a', 'b', 'c', 'd', 'e']) 19 | ___assertEqual(list(b), []) 20 | 21 | # test_sinkstate_callable 22 | # This used to fail 23 | def spam(state=[0]): 24 | i = state[0] 25 | state[0] = i+1 26 | if i == 10: 27 | raise AssertionError("shouldn't have gotten this far") 28 | return i 29 | b = iter(spam, 5) 30 | ___assertEqual(list(b), list(range(5))) 31 | ___assertEqual(list(b), []) 32 | 33 | # test_sinkstate_dict 34 | # XXX For a more thorough test, see towards the end of: 35 | # http://mail.python.org/pipermail/python-dev/2002-July/026512.html 36 | a = {1:1, 2:2, 0:0, 4:4, 3:3} 37 | for b in iter(a), a.keys(), a.items(), a.values(): 38 | b = iter(a) 39 | ___assertEqual(len(list(b)), 5) 40 | ___assertEqual(list(b), []) 41 | 42 | # test_sinkstate_range 43 | a = range(5) 44 | b = iter(a) 45 | ___assertEqual(list(b), list(range(5))) 46 | ___assertEqual(list(b), []) 47 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/lists/test_list_identity.py: -------------------------------------------------------------------------------- 1 | if(not ([] is not [])): raise Exception('list identity') 2 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/lists/test_list_simple.py: -------------------------------------------------------------------------------- 1 | if (not (list([]) == [])): raise Exception('List empty') 2 | l0_3 = [0, 1, 2, 3] 3 | l0_3_bis = list(l0_3) 4 | if (not (l0_3 == l0_3_bis)): raise Exception('List identity') 5 | if (not (l0_3 is not l0_3_bis)): raise Exception('List identity') 6 | if (not (list(()) == [])): raise Exception( 'List tuple') 7 | if (not (list((0, 1, 2, 3)), [0, 1, 2, 3])): raise Exception('List tuple 2') 8 | if (not (list('') == [])): raise Exception( 'List string 1') 9 | if (not (list('spam') == ['s', 'p', 'a', 'm'])): raise Exception( 'List string 2') 10 | 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/lists/test_list_truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not []) 2 | ___assertTrue([42]) 3 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/range/range-errs.py: -------------------------------------------------------------------------------- 1 | ___assertRaises(TypeError, range) 2 | ___assertRaises(TypeError, range, 1, 2, 3, 4) 3 | ___assertRaises(ValueError, range, 1, 2, 0) 4 | 5 | ___assertRaises(TypeError, range, 0.0, 2, 1) 6 | ___assertRaises(TypeError, range, 1, 2.0, 1) 7 | ___assertRaises(TypeError, range, 1, 2, 1.0) 8 | ___assertRaises(TypeError, range, 1e100, 1e101, 1e101) 9 | 10 | ___assertRaises(TypeError, range, 0, "spam") 11 | ___assertRaises(TypeError, range, 0, 42, "spam") 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/range/range-list.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(range(3)), [0, 1, 2]) 2 | ___assertEqual(list(range(1, 5)), [1, 2, 3, 4]) 3 | ___assertEqual(list(range(0)), []) 4 | ___assertEqual(list(range(-3)), []) 5 | ___assertEqual(list(range(1, 10, 3)), [1, 4, 7]) 6 | ___assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/range/range-vars.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | b = 100 3 | c = 50 4 | 5 | ___assertEqual(list(range(a, a+2)), [a, a+1]) 6 | ___assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) 7 | ___assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) 8 | 9 | seq = list(range(a, b, c)) 10 | ___assertIn(a, seq) 11 | ___assertNotIn(b, seq) 12 | ___assertEqual(len(seq), 2) 13 | 14 | seq = list(range(b, a, -c)) 15 | ___assertIn(b, seq) 16 | ___assertNotIn(a, seq) 17 | ___assertEqual(len(seq), 2) 18 | 19 | seq = list(range(-a, -b, -c)) 20 | ___assertIn(-a, seq) 21 | ___assertNotIn(-b, seq) 22 | ___assertEqual(len(seq), 2) 23 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/bound-and-free.py: -------------------------------------------------------------------------------- 1 | # var is bound and free in class 2 | 3 | def f(x): 4 | class C: 5 | def m(self): 6 | return x 7 | a = x 8 | return C 9 | 10 | inst = f(3)() 11 | ___assertEqual(inst.a, inst.m()) 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/extra-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder2(x): 2 | def extra(): # check freevars passing through non-use scopes 3 | def adder(y): 4 | return x + y 5 | return adder 6 | return extra() 7 | 8 | inc = make_adder2(1) 9 | plus10 = make_adder2(10) 10 | 11 | ___assertEqual(inc(1), 2) 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/freevar-in-method.py: -------------------------------------------------------------------------------- 1 | def test(): 2 | method_and_var = "var" 3 | class Test: 4 | def method_and_var(self): 5 | return "method" 6 | def test(self): 7 | return method_and_var 8 | def actual_global(self): 9 | return str("global") 10 | def str(self): 11 | return str(self) 12 | return Test() 13 | 14 | t = test() 15 | ___assertEqual(t.test(), "var") 16 | ___assertEqual(t.method_and_var(), "method") 17 | ___assertEqual(t.actual_global(), "global") 18 | 19 | method_and_var = "var" 20 | class Test: 21 | # this class is not nested, so the rules are different 22 | def method_and_var(self): 23 | return "method" 24 | def test(self): 25 | return method_and_var 26 | def actual_global(self): 27 | return str("global") 28 | def str(self): 29 | return str(self) 30 | 31 | t = Test() 32 | ___assertEqual(t.test(), "var") 33 | ___assertEqual(t.method_and_var(), "method") 34 | ___assertEqual(t.actual_global(), "global") 35 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/lambda1.py: -------------------------------------------------------------------------------- 1 | f1 = lambda x: lambda y: x + y 2 | inc = f1(1) 3 | plus10 = f1(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/lambda2.py: -------------------------------------------------------------------------------- 1 | f2 = lambda x: (lambda : lambda y: x + y)() 2 | inc = f2(1) 3 | plus10 = f2(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/lambda3.py: -------------------------------------------------------------------------------- 1 | f3 = lambda x: lambda y: global_x + y 2 | global_x = 1 3 | inc = f3(None) 4 | ___assertEqual(inc(2), 3) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/lambda4.py: -------------------------------------------------------------------------------- 1 | f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) 2 | g = f8(1, 2, 3) 3 | h = g(2, 4, 6) 4 | ___assertEqual(h(), 18) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/locals-class.py: -------------------------------------------------------------------------------- 1 | # This test verifies that calling locals() does not pollute 2 | # the local namespace of the class with free variables. Old 3 | # versions of Python had a bug, where a free variable being 4 | # passed through a class namespace would be inserted into 5 | # locals() by locals() or exec or a trace function. 6 | # 7 | # The real bug lies in frame code that copies variables 8 | # between fast locals and the locals dict, e.g. when executing 9 | # a trace function. 10 | 11 | def f(x): 12 | class C: 13 | x = 12 14 | def m(self): 15 | return x 16 | locals() 17 | return C 18 | 19 | ___assertEqual(f(1).x, 12) 20 | 21 | def f(x): 22 | class C: 23 | y = x 24 | def m(self): 25 | return x 26 | z = list(locals()) 27 | return C 28 | 29 | varnames = f(1).z 30 | ___assertNotIn("x", varnames) 31 | ___assertIn("y", varnames) 32 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/locals-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | def h(z): 4 | return y + z 5 | w = x + y 6 | y += 3 7 | return locals() 8 | return g 9 | 10 | d = f(2)(4) 11 | ___assertIn('h', d) 12 | del d['h'] 13 | ___assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) 14 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/mixed-freevars-and-cellvars.py: -------------------------------------------------------------------------------- 1 | def identity(x): 2 | return x 3 | 4 | def f(x, y, z): 5 | def g(a, b, c): 6 | a = a + x # 3 7 | def h(): 8 | # z * (4 + 9) 9 | # 3 * 13 10 | return identity(z * (b + y)) 11 | y = c + z # 9 12 | return h 13 | return g 14 | 15 | g = f(1, 2, 3) 16 | h = g(2, 4, 6) 17 | ___assertEqual(h(), 39) 18 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nearest-enclosing-scope.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | x = 42 # check that this masks binding in f() 4 | def h(z): 5 | return x + z 6 | return h 7 | return g(2) 8 | 9 | test_func = f(10) 10 | ___assertEqual(test_func(5), 47) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nested-nonlocal.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(): 3 | nonlocal x 4 | x -= 2 5 | def h(): 6 | nonlocal x 7 | x += 4 8 | return x 9 | return h 10 | return g 11 | 12 | g = f(1) 13 | h = g() 14 | ___assertEqual(h(), 3) 15 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nesting-global-no-free.py: -------------------------------------------------------------------------------- 1 | def make_adder4(): # XXX add exta level of indirection 2 | def nest(): 3 | def nest(): 4 | def adder(y): 5 | return global_x + y # check that plain old globals work 6 | return adder 7 | return nest() 8 | return nest() 9 | 10 | global_x = 1 11 | adder = make_adder4() 12 | ___assertEqual(adder(1), 2) 13 | 14 | global_x = 10 15 | ___assertEqual(adder(-2), 8) 16 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nesting-plus-free-ref-to-global.py: -------------------------------------------------------------------------------- 1 | def make_adder6(x): 2 | global global_nest_x 3 | def adder(y): 4 | return global_nest_x + y 5 | global_nest_x = x 6 | return adder 7 | 8 | inc = make_adder6(1) 9 | plus10 = make_adder6(10) 10 | 11 | ___assertEqual(inc(1), 11) # there's only one global 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nesting-through-class.py: -------------------------------------------------------------------------------- 1 | def make_adder5(x): 2 | class Adder: 3 | def __call__(self, y): 4 | return x + y 5 | return Adder() 6 | 7 | inc = make_adder5(1) 8 | plus10 = make_adder5(10) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nonlocal-class.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | nonlocal x 4 | x += 1 5 | def get(self): 6 | return x 7 | return c() 8 | 9 | c = f(0) 10 | ___assertEqual(c.get(), 1) 11 | ___assertNotIn("x", c.__class__.__dict__) 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nonlocal-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def inc(): 3 | nonlocal x 4 | x += 1 5 | return x 6 | def dec(): 7 | nonlocal x 8 | x -= 1 9 | return x 10 | return inc, dec 11 | 12 | inc, dec = f(0) 13 | ___assertEqual(inc(), 1) 14 | ___assertEqual(inc(), 2) 15 | ___assertEqual(dec(), 1) 16 | ___assertEqual(dec(), 0) 17 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/nonlocal-method.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | def inc(self): 4 | nonlocal x 5 | x += 1 6 | return x 7 | def dec(self): 8 | nonlocal x 9 | x -= 1 10 | return x 11 | return c() 12 | c = f(0) 13 | ___assertEqual(c.inc(), 1) 14 | ___assertEqual(c.inc(), 2) 15 | ___assertEqual(c.dec(), 1) 16 | ___assertEqual(c.dec(), 0) 17 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/recursion.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def fact(n): 3 | if n == 0: 4 | return 1 5 | else: 6 | return n * fact(n - 1) 7 | if x >= 0: 8 | return fact(x) 9 | else: 10 | raise ValueError("x must be >= 0") 11 | 12 | ___assertEqual(f(6), 720) 13 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/simple-and-rebinding.py: -------------------------------------------------------------------------------- 1 | def make_adder3(x): 2 | def adder(y): 3 | return x + y 4 | x = x + 1 # check tracking of assignment to x in defining scope 5 | return adder 6 | 7 | inc = make_adder3(0) 8 | plus10 = make_adder3(9) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/simple-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder(x): 2 | def adder(y): 3 | return x + y 4 | return adder 5 | 6 | inc = make_adder(1) 7 | plus10 = make_adder(10) 8 | 9 | ___assertEqual(inc(1), 2) 10 | ___assertEqual(plus10(-2), 8) 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/scope/unbound-local.py: -------------------------------------------------------------------------------- 1 | def errorInOuter(): 2 | print(y) 3 | def inner(): 4 | return y 5 | y = 1 6 | 7 | def errorInInner(): 8 | def inner(): 9 | return y 10 | inner() 11 | y = 1 12 | 13 | ___assertRaises(UnboundLocalError, errorInOuter) 14 | ___assertRaises(NameError, errorInInner) 15 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/tuple/tuple-add.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u += (2, 3) 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/tuple/tuple-constructors.py: -------------------------------------------------------------------------------- 1 | # calling built-in types without argument must return empty 2 | ___assertEqual(tuple(), ()) 3 | t0_3 = (0, 1, 2, 3) 4 | t0_3_bis = tuple(t0_3) 5 | ___assertTrue(t0_3 is t0_3_bis) 6 | ___assertEqual(tuple([]), ()) 7 | ___assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) 8 | ___assertEqual(tuple(''), ()) 9 | ___assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) 10 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/tuple/tuple-length.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len(()), 0) 2 | ___assertEqual(len((0,)), 1) 3 | ___assertEqual(len((0, 1, 2)), 3) 4 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/tuple/tuple-mul.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u *= 3 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/tuple/tuple-truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not ()) 2 | ___assertTrue((42, )) 3 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_booleans.py: -------------------------------------------------------------------------------- 1 | if 0 or 0: raise Exception('0 or 0 is true instead of false') 2 | if 1 and 1: pass 3 | else: raise Exception('1 and 1 is false instead of true') 4 | if not 1: raise Exception('not 1 is true instead of false') 5 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_comparisons.py: -------------------------------------------------------------------------------- 1 | if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass 2 | else: raise Exception('int comparisons failed') 3 | if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass 4 | else: raise Exception('float comparisons failed') 5 | if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass 6 | else: raise Exception('string comparisons failed') 7 | if None is None: pass 8 | else: raise Exception('identity test failed') 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_div_zero.py: -------------------------------------------------------------------------------- 1 | try: 5.0 / 0.0 2 | except ZeroDivisionError: pass 3 | else: raise Exception("5.0 / 0.0 didn't raise ZeroDivisionError") 4 | 5 | try: 5.0 // 0.0 6 | except ZeroDivisionError: pass 7 | else: raise Exception("5.0 // 0.0 didn't raise ZeroDivisionError") 8 | 9 | try: 5.0 % 0.0 10 | except ZeroDivisionError: pass 11 | else: raise Exception("5.0 % 0.0 didn't raise ZeroDivisionError") 12 | 13 | try: 5 / 0 14 | except ZeroDivisionError: pass 15 | else: raise Exception("5 / 0 didn't raise ZeroDivisionError") 16 | 17 | try: 5 // 0 18 | except ZeroDivisionError: pass 19 | else: raise Exception("5 // 0 didn't raise ZeroDivisionError") 20 | 21 | try: 5 % 0 22 | except ZeroDivisionError: pass 23 | else: raise Exception("5 % 0 didn't raise ZeroDivisionError") 24 | 25 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_floats.py: -------------------------------------------------------------------------------- 1 | if 12.0 + 24.0 != 36.0: raise Exception('float op +') 2 | if 12.0 + (-24.0) != -12.0: raise Exception('float op +/-') 3 | if (-12.0) + 24.0 != 12.0: raise Exception('float op -/+') 4 | if (-12.0) + (-24.0) != -36.0: raise Exception('float op -/+/-') 5 | if not 12.0 < 24.0: raise Exception('float op <') 6 | if not -24.0 < -12.0: raise Exception('float op < negative') 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_simple_string_ops.py: -------------------------------------------------------------------------------- 1 | if 'xyz' + 'abcde' != 'xyzabcde': raise Exception('string concatenation') 2 | if 'xyz'*3 != 'xyzxyzxyz': raise Exception('string repetition *3') 3 | if 0*'abcde' != '': raise Exception('string repetition 0*') 4 | if min('abc') != 'a' or max('abc') != 'c': raise Exception('min/max string') 5 | if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass 6 | else: raise Exception('in/not in string') 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_simple_strings.py: -------------------------------------------------------------------------------- 1 | if len('') != 0: raise Exception('len(\'\')') 2 | if len('a') != 1: raise Exception('len(\'a\')') 3 | if len('abcdef') != 6: raise Exception('len(\'abcdef\')') 4 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/test_string_slices.py: -------------------------------------------------------------------------------- 1 | a = '0123456789' 2 | if (not (a[::] == a)): raise Exception('Slice total') 3 | if (not (a[::2] == '02468')): raise Exception('Slice 2') 4 | if (not (a[1::2] == '13579')): raise Exception('Slice 1::2') 5 | if (not (a[::-1] =='9876543210')): raise Exception('Slice ::-1') 6 | if (not (a[::-2] == '97531')): raise Exception('Slice ::-2') 7 | if (not (a[3::-2] == '31')): raise Exception('Slice 3::-2') 8 | if (not (a[-100:100:] == a)): raise Exception('Slice -100::100') 9 | if (not (a[100:-100:-1] == a[::-1])): raise Exception('Slice triple') 10 | if (not (a[-100:100:2] == '02468')): raise Exception('Slice triple 2') 11 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/types_truthy1.py: -------------------------------------------------------------------------------- 1 | if None: raise Exception('None is true instead of false') 2 | if 0: raise Exception('0 is true instead of false') 3 | if 0.0: raise Exception('0.0 is true instead of false') 4 | if '': raise Exception('\'\' is true instead of false') 5 | if not 1: raise Exception('1 is false instead of true') 6 | if not 1.0: raise Exception('1.0 is false instead of true') 7 | if not 'x': raise Exception('\'x\' is false instead of true') 8 | if not {'x': 1}: raise Exception('{\'x\': 1} is false instead of true') 9 | -------------------------------------------------------------------------------- /design4/cs173-python/python-reference/types/types_truthy2.py: -------------------------------------------------------------------------------- 1 | def f(): pass 2 | class C: pass 3 | x = C() 4 | if not f: raise Exception('f is false instead of true') 5 | if not C: raise Exception('C is false instead of true') 6 | if not x: raise Exception('x is false instead of true') 7 | -------------------------------------------------------------------------------- /design4/cs173-python/python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (print-only-errors true) 4 | 5 | (define-type PyExp 6 | [PySeq (es : (listof PyExp))] 7 | [PyNum (n : number)] 8 | [PyStr (s : string)] 9 | [PyBool (b : boolean)] 10 | [PyNone] 11 | [PyDict (fs : (hashof PyExp PyExp))] 12 | [PyId (x : symbol)] 13 | [PyFunDef (name : symbol) (args : PyArgT) (body : PyExp)] 14 | [PyLambda (args : PyArgT) (body : PyExp)] 15 | [PyApp (fun : PyExp) (args : (listof PyExp))] 16 | [PyReturn (v : PyExp)] 17 | ;; targets are PyIds 18 | [PyAssign (targets : (listof PyExp)) (value : PyExp)] 19 | [PyIf (test : PyExp) (body : PyExp) (orelse : PyExp)] 20 | 21 | [PyBoolOp (op : symbol) (arg1 : PyExp) (arg2 : PyExp)] 22 | [PyBinOp (op : symbol) (left : PyExp) (right : PyExp)] 23 | [PyUnaryOp (op : symbol) (arg : PyExp)] 24 | [PyCompare (ops : (listof symbol)) (cmps : (listof PyExp)) (lft : PyExp)] 25 | [PyPass] 26 | 27 | [PyWhile (tst : PyExp) (body : PyExp)] 28 | [PyBreak] 29 | [PyContinue] 30 | 31 | ; a placeholder that will go away once all of python exists as 32 | ; PyExprs. This way we can parse everything, and only error if 33 | ; we actually try to execute something we haven't defined yet. 34 | [PyUndefined]) 35 | 36 | 37 | (define-type PyArgT 38 | ;; to add later - varargs, kwargs, etc 39 | [PyArgs (args : (listof symbol)) (defaults : (listof PyExp))]) -------------------------------------------------------------------------------- /design4/cs173-python/python-tests.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | ;; this module exercises the whole stack on some toy examples (no python-lib) 4 | 5 | (require "python-interp.rkt" 6 | "python-desugar.rkt" 7 | "python-desugar-core.rkt" 8 | "python-cps.rkt" 9 | "python-syntax.rkt" 10 | "python-micro-syntax.rkt" 11 | ) 12 | 13 | 14 | (define (run [e : PyExp]) : UVal 15 | (interp (run-cps (desugar-core (desugar e))))) 16 | 17 | (test (run (PyNum 10)) (VNum 10)) 18 | (test (run (PyStr "s")) (VStr "s")) 19 | (test (run (PyIf (PyBool true) (PyNum 1) (PyNum 2))) (VNum 1)) 20 | (test (run (PyWhile (PyBool true) (PyIf (PyBool true) (PyBreak) (PyContinue)))) (VNone)) 21 | -------------------------------------------------------------------------------- /design5/parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /design5/python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | elif t in [bytes]: return {'nodetype': 'Bytes', 'value': str(v)} 22 | else: 23 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 24 | % v) 25 | 26 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 27 | n_dict['nodetype'] = n.__class__.__name__ 28 | return n_dict 29 | 30 | if __name__ == '__main__': 31 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 32 | 33 | -------------------------------------------------------------------------------- /design5/python-primitives.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (require "python-core-syntax.rkt") 4 | 5 | #| 6 | 7 | Since there may end up being a large number of primitives that you 8 | implement for python, here is a suggested factoring into a separate 9 | file. You can add new primitives here by adding new symbols to the 10 | dispatch. You might also choose to add more than single-arity 11 | primitives here. 12 | 13 | |# 14 | 15 | (require (typed-in racket/base [display : (string -> void)])) 16 | 17 | (define (pretty arg) : string 18 | (type-case CVal arg 19 | [VNum (n) (to-string n)] 20 | [VStr (s) s] 21 | [VTrue () "True"] 22 | [VClosure (env args body) (error 'prim "Can't print closures yet")] 23 | ;;Non-TA code: 24 | [VNone () "void"] 25 | [VFalse () "False"] 26 | [VPass () ""] 27 | [VUnbound () "Unbound"] 28 | )) 29 | 30 | 31 | (define (print arg) 32 | (display (pretty arg))) 33 | 34 | (define (python-prim1 op arg) 35 | (case op 36 | [(print) (begin (print arg) arg)])) 37 | 38 | -------------------------------------------------------------------------------- /design5/python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (define-type PyExpr 4 | [PySeq (es : (listof PyExpr))] 5 | [PyNum (n : number)] 6 | [PyId (x : symbol)] 7 | [PyApp (fun : PyExpr) (args : (listof PyExpr))] 8 | ;;Made by me: 9 | [PyStr (s : string)] 10 | [PyIf (test : PyExpr) (then : (listof PyExpr)) (orelse : (listof PyExpr))] 11 | [PyBoolop (boolop : symbol) (values : (listof PyExpr))] 12 | [PyUnaryOp (op : symbol) (arg : PyExpr)] 13 | [PyBinOp (op : symbol) (left : PyExpr) (right : PyExpr)] 14 | [PyCompare (left : PyExpr) (ops : (listof symbol)) (comparators : (listof PyExpr))] 15 | [PyPass] 16 | [PyNone] 17 | [PyLambda (args : (listof symbol)) (body : PyExpr)] 18 | [PyRaise (exc : PyExpr)] ;(cause : PyExpr)] 19 | [PyGlobal (ids : (listof symbol))] 20 | [PyNonlocal (ids : (listof symbol))] 21 | [PyAssign (targets : (listof PyExpr)) (value : PyExpr)] 22 | [PySet (lhs : PyExpr) (value : PyExpr)] 23 | [PyModule (program : PyExpr)] 24 | [PyGlobalEnv] 25 | 26 | [PyDef (name : symbol) (args : (listof symbol)) (body : PyExpr)] ;; deffun 27 | [PyReturn (value : PyExpr)] ;; return 28 | 29 | [Py-NotExist] ;;THIS IS HERE ONLY SO THAT python-desugar won't complain about having completed all of the expressions 30 | ) 31 | 32 | -------------------------------------------------------------------------------- /get-structured-python.rkt: -------------------------------------------------------------------------------- 1 | #lang plai 2 | 3 | (require "python-syntax.rkt") 4 | (require racket/match 5 | racket/list) 6 | 7 | #| 8 | 9 | Python parses as a JSON structure that we export from Python's ast 10 | module. You should use this file to turn it into a plai-typed data 11 | structure that you define in python-syntax.rkt 12 | 13 | |# 14 | 15 | (define (get-structured-python pyjson) 16 | (match pyjson 17 | [(hash-table ('nodetype "Module") ('body expr-list)) 18 | (PySeq (map get-structured-python expr-list))] 19 | [(hash-table ('nodetype "Expr") ('value expr)) 20 | (get-structured-python expr)] 21 | [(hash-table ('nodetype "Call") 22 | ('keywords keywords) ;; ignoring keywords for now 23 | ('kwargs kwargs) ;; ignoring kwargs for now 24 | ('starargs starargs) ;; ignoring starargs for now 25 | ('args args-list) 26 | ('func func-expr)) 27 | (PyApp (get-structured-python func-expr) 28 | (map get-structured-python args-list))] 29 | [(hash-table ('nodetype "Name") 30 | ('ctx _) ;; ignoring ctx for now 31 | ('id id)) 32 | (PyId (string->symbol id))] 33 | [(hash-table ('nodetype "Num") 34 | ('n n)) 35 | (PyNum n)] 36 | [_ (error 'parse "Haven't handled a case yet")])) 37 | 38 | -------------------------------------------------------------------------------- /parse-python.rkt: -------------------------------------------------------------------------------- 1 | #lang racket/base 2 | 3 | (require racket/system racket/list) 4 | (require (planet dherman/json:4:0)) 5 | 6 | (define (get-parsed-json input-port python-path) 7 | (define stdout (open-output-string "stdout")) 8 | (define stderr (open-output-string "stderr")) 9 | (define proc (process*/ports stdout input-port stderr python-path "python-parser.py")) 10 | ((fifth proc) 'wait) 11 | (define err-output (get-output-string stderr)) 12 | (when (not (equal? err-output "")) 13 | (error 'parse (format "Couldn't parse python file with python-parser.py. Error was: \n ~a" err-output))) 14 | (define std-output (get-output-string stdout)) 15 | (json->jsexpr std-output)) 16 | 17 | (define (parse-python/string s python-path) 18 | (parse-python/port (open-input-string s) python-path)) 19 | 20 | (define (parse-python/port port python-path) 21 | (get-parsed-json port python-path)) 22 | 23 | (provide parse-python/port parse-python/string) 24 | 25 | -------------------------------------------------------------------------------- /py-prelude.py: -------------------------------------------------------------------------------- 1 | def ___assertEqual(l, r): 2 | assert(l == r) 3 | 4 | def ___assertNotEqual(l, r): 5 | assert(not (l == r)) 6 | 7 | def ___assertTrue(v): 8 | assert(v) 9 | 10 | def ___assertFalse(v): 11 | assert(not v) 12 | 13 | def ___assertIs(l, r): 14 | assert(l is r) 15 | 16 | def ___assertIsNot(l, r): 17 | assert(not (l is r)) 18 | 19 | def ___assertIn(l, r): 20 | assert(l in r) 21 | 22 | def ___assertNotIn(l, r): 23 | assert(not (l in r)) 24 | 25 | def ___assertRaises(e, f, *args): 26 | try: 27 | f(*args) 28 | except e as the_exn: 29 | return 30 | else: 31 | assert(False) 32 | assert(False) 33 | 34 | def ___fail(): 35 | assert(False) 36 | -------------------------------------------------------------------------------- /python-core-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | #| 4 | 5 | This is the core language; it is just borrowing a few things from 6 | ParselTongue. 7 | 8 | |# 9 | 10 | (define-type CExp 11 | [CNum (n : number)] 12 | [CStr (s : string)] 13 | [CTrue] 14 | [CSeq (e1 : CExp) (e2 : CExp)] 15 | [CError (e1 : CExp)] 16 | [CIf (test : CExp) (then : CExp) (else : CExp)] 17 | [CId (x : symbol)] 18 | [CLet (x : symbol) (bind : CExp) (body : CExp)] 19 | [CApp (fun : CExp) (args : (listof CExp))] 20 | [CFunc (args : (listof symbol)) (body : CExp)] 21 | [CPrim1 (prim : symbol) (arg : CExp)]) 22 | 23 | (define-type CVal 24 | [VNum (n : number)] 25 | [VStr (s : string)] 26 | [VTrue] 27 | [VClosure (env : Env) (args : (listof symbol)) (body : CExp)]) 28 | 29 | (define-type-alias Env (hashof symbol CVal)) 30 | 31 | -------------------------------------------------------------------------------- /python-desugar.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (require "python-syntax.rkt" 4 | "python-core-syntax.rkt") 5 | 6 | (define (desugar expr) 7 | (type-case PyExpr expr 8 | [PySeq (es) (foldl (lambda (e1 e2) (CSeq e2 (desugar e1))) (desugar (first es)) (rest es))] 9 | [PyNum (n) (CNum n)] 10 | [PyApp (f args) (CApp (desugar f) (map desugar args))] 11 | [PyId (x) (CId x)])) 12 | -------------------------------------------------------------------------------- /python-parser.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | import json 4 | 5 | class JSONVisitorException(Exception): 6 | pass 7 | 8 | class QuickVisitor(ast.NodeVisitor): 9 | def generic_visit(self, n): 10 | if (not (isinstance(n, ast.AST))): 11 | raise JSONVisitorException("Unexpected error: Non-ast passed to visit. Please report to the TAs.") 12 | fields = ast.iter_fields(n) 13 | 14 | def get_item(v): 15 | t = type(v) 16 | if v is None: return None 17 | elif t == list: return list(map (lambda elt: get_item(elt), v)) 18 | elif isinstance(v, ast.AST): return self.visit(v) 19 | elif t in [int, float, str]: return v 20 | elif t in [complex]: return {'nodetype': 'Complex', 'value': str(v)} 21 | elif t in [bytes]: return {'nodetype': 'Bytes', 'value': str(v)} 22 | else: 23 | raise JSONVisitorException("Unexpected error: Missed case: %s. Please report to the TAs." 24 | % v) 25 | 26 | n_dict = dict([(f,get_item(v)) for (f,v) in fields]) 27 | n_dict['nodetype'] = n.__class__.__name__ 28 | return n_dict 29 | 30 | if __name__ == '__main__': 31 | print(json.dumps(QuickVisitor().visit(ast.parse(sys.stdin.read())))) 32 | 33 | -------------------------------------------------------------------------------- /python-primitives.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (require "python-core-syntax.rkt") 4 | 5 | #| 6 | 7 | Since there may end up being a large number of primitives that you 8 | implement for python, here is a suggested factoring into a separate 9 | file. You can add new primitives here by adding new symbols to the 10 | dispatch. You might also choose to add more than single-arity 11 | primitives here. 12 | 13 | |# 14 | 15 | (require (typed-in racket/base [display : (string -> void)])) 16 | 17 | (define (pretty arg) 18 | (type-case CVal arg 19 | [VNum (n) (to-string n)] 20 | [VStr (s) s] 21 | [VTrue () "true"] 22 | [VClosure (env args body) (error 'prim "Can't print closures yet")])) 23 | 24 | 25 | (define (print arg) 26 | (display (pretty arg))) 27 | 28 | (define (python-prim1 op arg) 29 | (case op 30 | [(print) (begin (print arg) arg)])) 31 | 32 | -------------------------------------------------------------------------------- /python-reference/bool/bool-callable.py: -------------------------------------------------------------------------------- 1 | ___assertIs(callable(len), True) 2 | ___assertIs(callable(1), False) 3 | -------------------------------------------------------------------------------- /python-reference/bool/bool-compare-list-dict.py: -------------------------------------------------------------------------------- 1 | x = [1] 2 | ___assertIs(x is x, True) 3 | ___assertIs(x is not x, False) 4 | 5 | ___assertIs(1 in x, True) 6 | ___assertIs(0 in x, False) 7 | ___assertIs(1 not in x, False) 8 | ___assertIs(0 not in x, True) 9 | 10 | x = {1: 2} 11 | ___assertIs(x is x, True) 12 | ___assertIs(x is not x, False) 13 | 14 | ___assertIs(1 in x, True) 15 | ___assertIs(0 in x, False) 16 | ___assertIs(1 not in x, False) 17 | ___assertIs(0 not in x, True) 18 | 19 | ___assertIs(not True, False) 20 | ___assertIs(not False, True) 21 | -------------------------------------------------------------------------------- /python-reference/bool/bool-compare.py: -------------------------------------------------------------------------------- 1 | ___assertIs(1==1, True) 2 | ___assertIs(1==0, False) 3 | ___assertIs(0<1, True) 4 | ___assertIs(1<0, False) 5 | ___assertIs(0<=0, True) 6 | ___assertIs(1<=0, False) 7 | ___assertIs(1>0, True) 8 | ___assertIs(1>1, False) 9 | ___assertIs(1>=1, True) 10 | ___assertIs(0>=1, False) 11 | ___assertIs(0!=1, True) 12 | ___assertIs(0!=0, False) 13 | -------------------------------------------------------------------------------- /python-reference/bool/bool-convert.py: -------------------------------------------------------------------------------- 1 | ___assertIs(bool(10), True) 2 | ___assertIs(bool(1), True) 3 | ___assertIs(bool(-1), True) 4 | ___assertIs(bool(0), False) 5 | ___assertIs(bool("hello"), True) 6 | ___assertIs(bool(""), False) 7 | ___assertIs(bool(), False) 8 | -------------------------------------------------------------------------------- /python-reference/bool/bool-float.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(float(False), 0.0) 2 | ___assertIsNot(float(False), False) 3 | ___assertEqual(float(True), 1.0) 4 | ___assertIsNot(float(True), True) 5 | -------------------------------------------------------------------------------- /python-reference/bool/bool-int.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(int(False), 0) 2 | ___assertIsNot(int(False), False) 3 | ___assertEqual(int(True), 1) 4 | ___assertIsNot(int(True), True) 5 | -------------------------------------------------------------------------------- /python-reference/bool/bool-isinstance.py: -------------------------------------------------------------------------------- 1 | ___assertIs(isinstance(True, bool), True) 2 | ___assertIs(isinstance(False, bool), True) 3 | ___assertIs(isinstance(True, int), True) 4 | ___assertIs(isinstance(False, int), True) 5 | ___assertIs(isinstance(1, bool), False) 6 | ___assertIs(isinstance(0, bool), False) 7 | -------------------------------------------------------------------------------- /python-reference/bool/bool-math.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(+False, 0) 2 | ___assertIsNot(+False, False) 3 | ___assertEqual(-False, 0) 4 | ___assertIsNot(-False, False) 5 | ___assertEqual(abs(False), 0) 6 | ___assertIsNot(abs(False), False) 7 | ___assertEqual(+True, 1) 8 | ___assertIsNot(+True, True) 9 | ___assertEqual(-True, -1) 10 | ___assertEqual(abs(True), 1) 11 | ___assertIsNot(abs(True), True) 12 | ___assertEqual(~False, -1) 13 | ___assertEqual(~True, -2) 14 | 15 | ___assertEqual(False+2, 2) 16 | ___assertEqual(True+2, 3) 17 | ___assertEqual(2+False, 2) 18 | ___assertEqual(2+True, 3) 19 | 20 | ___assertEqual(False+False, 0) 21 | ___assertIsNot(False+False, False) 22 | ___assertEqual(False+True, 1) 23 | ___assertIsNot(False+True, True) 24 | ___assertEqual(True+False, 1) 25 | ___assertIsNot(True+False, True) 26 | ___assertEqual(True+True, 2) 27 | 28 | ___assertEqual(True-True, 0) 29 | ___assertIsNot(True-True, False) 30 | ___assertEqual(False-False, 0) 31 | ___assertIsNot(False-False, False) 32 | ___assertEqual(True-False, 1) 33 | ___assertIsNot(True-False, True) 34 | ___assertEqual(False-True, -1) 35 | 36 | ___assertEqual(True*1, 1) 37 | ___assertEqual(False*1, 0) 38 | ___assertIsNot(False*1, False) 39 | 40 | ___assertEqual(True/1, 1) 41 | ___assertIsNot(True/1, True) 42 | ___assertEqual(False/1, 0) 43 | ___assertIsNot(False/1, False) 44 | -------------------------------------------------------------------------------- /python-reference/bool/bool-str.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(str(False), 'False') 2 | ___assertEqual(str(True), 'True') 3 | -------------------------------------------------------------------------------- /python-reference/builtin/all.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(all([2, 4, 6]), True) 2 | ___assertEqual(all([2, None, 6]), False) 3 | ___assertRaises(TypeError, all, 10) # Non-iterable 4 | ___assertRaises(TypeError, all) # No args 5 | ___assertRaises(TypeError, all, [2, 4, 6], []) # Too many args 6 | ___assertEqual(all([]), True) # Empty iterator 7 | S = [50, 60] 8 | ___assertEqual(all(x > 42 for x in S), True) 9 | S = [50, 40, 60] 10 | ___assertEqual(all(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /python-reference/builtin/any.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(any([None, None, None]), False) 2 | ___assertEqual(any([None, 4, None]), True) 3 | ___assertRaises(TypeError, any, 10) # Non-iterable 4 | ___assertRaises(TypeError, any) # No args 5 | ___assertRaises(TypeError, any, [2, 4, 6], []) # Too many args 6 | ___assertEqual(any([]), False) # Empty iterator 7 | S = [40, 60, 30] 8 | ___assertEqual(any(x > 42 for x in S), True) 9 | S = [10, 20, 30] 10 | ___assertEqual(any(x > 42 for x in S), False) 11 | -------------------------------------------------------------------------------- /python-reference/builtin/callable.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(callable(len)) 2 | ___assertFalse(callable("a")) 3 | ___assertTrue(callable(callable)) 4 | ___assertTrue(callable(lambda x, y: x + y)) 5 | 6 | def f(): pass 7 | ___assertTrue(callable(f)) 8 | 9 | class C1: 10 | def meth(self): pass 11 | ___assertTrue(callable(C1)) 12 | c = C1() 13 | ___assertTrue(callable(c.meth)) 14 | ___assertFalse(callable(c)) 15 | 16 | -------------------------------------------------------------------------------- /python-reference/builtin/filter.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) 2 | ___assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) 3 | ___assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) 4 | def badfunc(): 5 | pass 6 | ___assertRaises(TypeError, list, filter(badfunc, range(5))) 7 | 8 | # test bltinmodule.c::filtertuple() 9 | ___assertEqual(list(filter(None, (1, 2))), [1, 2]) 10 | ___assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) 11 | ___assertRaises(TypeError, list, filter(42, (1, 2))) 12 | -------------------------------------------------------------------------------- /python-reference/builtin/isinstance.py: -------------------------------------------------------------------------------- 1 | class C: 2 | pass 3 | class D(C): 4 | pass 5 | class E: 6 | pass 7 | c = C() 8 | d = D() 9 | e = E() 10 | ___assertTrue(isinstance(c, C)) 11 | ___assertTrue(isinstance(d, C)) 12 | ___assertTrue(not isinstance(e, C)) 13 | ___assertTrue(not isinstance(c, D)) 14 | ___assertTrue(not isinstance('foo', E)) 15 | ___assertRaises(TypeError, isinstance, E, 'foo') 16 | ___assertRaises(TypeError, isinstance) 17 | -------------------------------------------------------------------------------- /python-reference/builtin/len.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len('123'), 3) 2 | ___assertEqual(len(()), 0) 3 | ___assertEqual(len((1, 2, 3, 4)), 4) 4 | ___assertEqual(len([1, 2, 3, 4]), 4) 5 | ___assertEqual(len({}), 0) 6 | ___assertEqual(len({'a':1, 'b': 2}), 2) 7 | -------------------------------------------------------------------------------- /python-reference/dict/dict-bool.py: -------------------------------------------------------------------------------- 1 | ___assertIs(not {}, True) 2 | ___assertTrue({1: 2}) 3 | ___assertIs(bool({}), False) 4 | ___assertIs(bool({1: 2}), True) 5 | -------------------------------------------------------------------------------- /python-reference/dict/dict-clear.py: -------------------------------------------------------------------------------- 1 | d = {1:1, 2:2, 3:3} 2 | d.clear() 3 | ___assertEqual(d, {}) 4 | 5 | ___assertRaises(TypeError, d.clear, None) 6 | -------------------------------------------------------------------------------- /python-reference/dict/dict-contains.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertNotIn('a', d) 3 | ___assertFalse('a' in d) 4 | ___assertTrue('a' not in d) 5 | d = {'a': 1, 'b': 2} 6 | ___assertIn('a', d) 7 | ___assertIn('b', d) 8 | ___assertNotIn('c', d) 9 | -------------------------------------------------------------------------------- /python-reference/dict/dict-get.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertIs(d.get('c'), None) 3 | ___assertEqual(d.get('c', 3), 3) 4 | d = {'a': 1, 'b': 2} 5 | ___assertIs(d.get('c'), None) 6 | ___assertEqual(d.get('c', 3), 3) 7 | ___assertEqual(d.get('a'), 1) 8 | ___assertEqual(d.get('a', 3), 1) 9 | ___assertRaises(TypeError, d.get) 10 | ___assertRaises(TypeError, d.get, None, None, None) 11 | -------------------------------------------------------------------------------- /python-reference/dict/dict-getitem.py: -------------------------------------------------------------------------------- 1 | d = {'a': 1, 'b': 2} 2 | ___assertEqual(d['a'], 1) 3 | ___assertEqual(d['b'], 2) 4 | d['c'] = 3 5 | d['a'] = 4 6 | ___assertEqual(d['c'], 3) 7 | ___assertEqual(d['a'], 4) 8 | del d['b'] 9 | ___assertEqual(d, {'a': 4, 'c': 3}) 10 | 11 | ___assertRaises(TypeError, d.__getitem__) 12 | 13 | -------------------------------------------------------------------------------- /python-reference/dict/dict-items.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.items()), set()) 3 | 4 | d = {1:2} 5 | ___assertEqual(set(d.items()), {(1, 2)}) 6 | ___assertRaises(TypeError, d.items, None) 7 | -------------------------------------------------------------------------------- /python-reference/dict/dict-keys.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.keys()), set()) 3 | d = {'a': 1, 'b': 2} 4 | k = d.keys() 5 | ___assertIn('a', d) 6 | ___assertIn('b', d) 7 | ___assertRaises(TypeError, d.keys, None) 8 | -------------------------------------------------------------------------------- /python-reference/dict/dict-set-keys.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.keys() 2 | k2 = {1:1, 2:2, 3:3}.keys() 3 | k3 = {4:4}.keys() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {1,2}) 7 | ___assertEqual(k2 - k1, {3}) 8 | ___assertEqual(k3 - k1, {4}) 9 | ___assertEqual(k1 & k2, {1,2}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {1,2,3}) 12 | ___assertEqual(k1 ^ k2, {3}) 13 | ___assertEqual(k1 ^ k3, {1,2,4}) 14 | -------------------------------------------------------------------------------- /python-reference/dict/dict-update.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | d.update({1:100}) 3 | d.update({2:20}) 4 | d.update({1:1, 2:2, 3:3}) 5 | ___assertEqual(d, {1:1, 2:2, 3:3}) 6 | 7 | d.update() 8 | ___assertEqual(d, {1:1, 2:2, 3:3}) 9 | 10 | ___assertRaises((TypeError, AttributeError), d.update, None) 11 | -------------------------------------------------------------------------------- /python-reference/dict/dict-values-set.py: -------------------------------------------------------------------------------- 1 | k1 = {1:1, 2:2}.items() 2 | k2 = {1:1, 2:2, 3:3}.items() 3 | k3 = {4:4}.items() 4 | 5 | ___assertEqual(k1 - k2, set()) 6 | ___assertEqual(k1 - k3, {(1,1), (2,2)}) 7 | ___assertEqual(k2 - k1, {(3,3)}) 8 | ___assertEqual(k3 - k1, {(4,4)}) 9 | ___assertEqual(k1 & k2, {(1,1), (2,2)}) 10 | ___assertEqual(k1 & k3, set()) 11 | ___assertEqual(k1 | k2, {(1,1), (2,2), (3,3)}) 12 | ___assertEqual(k1 ^ k2, {(3,3)}) 13 | ___assertEqual(k1 ^ k3, {(1,1), (2,2), (4,4)}) 14 | -------------------------------------------------------------------------------- /python-reference/dict/dict-values.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | ___assertEqual(set(d.values()), set()) 3 | d = {1:2} 4 | ___assertEqual(set(d.values()), {2}) 5 | ___assertRaises(TypeError, d.values, None) 6 | -------------------------------------------------------------------------------- /python-reference/exceptions/except-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | except KeyError: 8 | pass 9 | raise 10 | ___assertRaises(TypeError, reraise) 11 | -------------------------------------------------------------------------------- /python-reference/exceptions/invalid-reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise 3 | except RuntimeError as e: 4 | ___assertIn("No active exception", str(e)) 5 | else: 6 | ___fail("No exception raised") 7 | -------------------------------------------------------------------------------- /python-reference/exceptions/nested-else.py: -------------------------------------------------------------------------------- 1 | hit_else = False 2 | hit_finally = False 3 | hit_except = False 4 | hit_inner_except = False 5 | hit_inner_else = False 6 | 7 | try: 8 | try: 9 | pass 10 | except: 11 | hit_inner_except = True 12 | else: 13 | hit_inner_else = True 14 | 15 | raise Exception('outer exception') 16 | except: 17 | hit_except = True 18 | else: 19 | hit_else = True 20 | finally: 21 | hit_finally = True 22 | 23 | ___assertFalse(hit_inner_except) 24 | ___assertTrue(hit_inner_else) 25 | ___assertFalse(hit_else) 26 | ___assertTrue(hit_finally) 27 | ___assertTrue(hit_except) 28 | -------------------------------------------------------------------------------- /python-reference/exceptions/nested-reraise.py: -------------------------------------------------------------------------------- 1 | def nested_reraise(): 2 | raise 3 | def reraise(): 4 | try: 5 | raise TypeError("foo") 6 | except: 7 | nested_reraise() 8 | ___assertRaises(TypeError, reraise) 9 | -------------------------------------------------------------------------------- /python-reference/exceptions/nested.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | hit_inner_except = False 3 | hit_inner_finally = False 4 | 5 | try: 6 | try: 7 | raise Exception('inner exception') 8 | except: 9 | hit_inner_except = True 10 | finally: 11 | hit_inner_finally = True 12 | finally: 13 | hit_finally = True 14 | 15 | ___assertTrue(hit_inner_except) 16 | ___assertTrue(hit_inner_finally) 17 | ___assertTrue(hit_finally) 18 | -------------------------------------------------------------------------------- /python-reference/exceptions/reraise.py: -------------------------------------------------------------------------------- 1 | try: 2 | try: 3 | raise IndexError() 4 | except IndexError as e: 5 | exc1 = e 6 | raise 7 | except IndexError as exc2: 8 | ___assertTrue(exc1 is exc2) 9 | else: 10 | ___fail("No exception raised") 11 | -------------------------------------------------------------------------------- /python-reference/exceptions/test-finally-reraise.py: -------------------------------------------------------------------------------- 1 | def reraise(): 2 | try: 3 | raise TypeError("foo") 4 | except: 5 | try: 6 | raise KeyError("caught") 7 | finally: 8 | raise 9 | ___assertRaises(KeyError, reraise) 10 | -------------------------------------------------------------------------------- /python-reference/exceptions/test-try-except-else.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | raise Exception('foo!') 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_else) 12 | ___assertTrue(hit_except) 13 | -------------------------------------------------------------------------------- /python-reference/exceptions/test-try-except-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | pass 5 | except: 6 | hit_except = True 7 | 8 | ___assertFalse(hit_except) 9 | -------------------------------------------------------------------------------- /python-reference/exceptions/test-try-except.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | 3 | try: 4 | raise Exception('ahoy!') 5 | except: 6 | hit_except = True 7 | 8 | ___assertTrue(hit_except) 9 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-except-else-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | pass 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertFalse(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertTrue(hit_else) 17 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-except-else-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | hit_finally = False 4 | 5 | try: 6 | raise Exception('nyaa!') 7 | except: 8 | hit_except = True 9 | else: 10 | hit_else = True 11 | finally: 12 | hit_finally = True 13 | 14 | ___assertTrue(hit_except) 15 | ___assertTrue(hit_finally) 16 | ___assertFalse(hit_else) 17 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-except-else-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_else = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | else: 9 | hit_else = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_else) 13 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-except-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | pass 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertFalse(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-except-finally.py: -------------------------------------------------------------------------------- 1 | hit_except = False 2 | hit_finally = False 3 | 4 | try: 5 | raise Exception('yarr!') 6 | except: 7 | hit_except = True 8 | finally: 9 | hit_finally = True 10 | 11 | ___assertTrue(hit_except) 12 | ___assertTrue(hit_finally) 13 | -------------------------------------------------------------------------------- /python-reference/exceptions/try-finally-no-exception.py: -------------------------------------------------------------------------------- 1 | hit_finally = False 2 | 3 | try: 4 | pass 5 | finally: 6 | hit_finally = True 7 | 8 | ___assertTrue(hit_finally) 9 | -------------------------------------------------------------------------------- /python-reference/iter/iter-comprehensions.py: -------------------------------------------------------------------------------- 1 | # Test result of triple loop (too big to inline) 2 | TRIPLETS = [(0, 0, 0), (0, 0, 1), (0, 0, 2), 3 | (0, 1, 0), (0, 1, 1), (0, 1, 2), 4 | (0, 2, 0), (0, 2, 1), (0, 2, 2), 5 | 6 | (1, 0, 0), (1, 0, 1), (1, 0, 2), 7 | (1, 1, 0), (1, 1, 1), (1, 1, 2), 8 | (1, 2, 0), (1, 2, 1), (1, 2, 2), 9 | 10 | (2, 0, 0), (2, 0, 1), (2, 0, 2), 11 | (2, 1, 0), (2, 1, 1), (2, 1, 2), 12 | (2, 2, 0), (2, 2, 1), (2, 2, 2)] 13 | 14 | 15 | seq = range(3) 16 | res = [] 17 | for i in iter(seq): 18 | for j in iter(seq): 19 | for k in iter(seq): 20 | res.append((i, j, k)) 21 | ___assertEqual(res, TRIPLETS) 22 | 23 | seq = range(3) 24 | res = [(i, j, k) for i in seq for j in seq for k in seq] 25 | ___assertEqual(res, TRIPLETS) 26 | -------------------------------------------------------------------------------- /python-reference/iter/iter-misc.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | 20 | check_for_loop(iter((0,1,2,3,4,5,6,7,8,9)), list(range(10))) 21 | check_for_loop(iter(range(10)), list(range(10))) 22 | check_for_loop(iter("abcde"), ["a", "b", "c", "d", "e"]) 23 | 24 | dict = {} 25 | for i in range(10): 26 | dict[i] = None 27 | check_for_loop(dict, list(dict.keys())) 28 | -------------------------------------------------------------------------------- /python-reference/iter/iter-simple.py: -------------------------------------------------------------------------------- 1 | # Helper to check that an iterator returns a given sequence 2 | def check_iterator(it, seq): 3 | res = [] 4 | while 1: 5 | try: 6 | val = next(it) 7 | except StopIteration: 8 | break 9 | res.append(val) 10 | ___assertEqual(res, seq) 11 | 12 | # Helper to check that a for loop generates a given sequence 13 | def check_for_loop(expr, seq): 14 | res = [] 15 | for val in expr: 16 | res.append(val) 17 | ___assertEqual(res, seq) 18 | 19 | # Test basic use of iter() function 20 | check_iterator(iter(range(10)), list(range(10))) 21 | 22 | # Test that iter(iter(x)) is the same as iter(x) 23 | seq = list(range(10)) 24 | it = iter(seq) 25 | it2 = iter(it) 26 | ___assertTrue(it is it2) 27 | 28 | check_for_loop(iter(range(10)), list(range(10))) 29 | 30 | check_for_loop(iter([]), []) 31 | -------------------------------------------------------------------------------- /python-reference/iter/iter-stop.py: -------------------------------------------------------------------------------- 1 | # test_sinkstate_list 2 | # This used to fail 3 | a = list(range(5)) 4 | b = iter(a) 5 | ___assertEqual(list(b), list(range(5))) 6 | a.extend(range(5, 10)) 7 | ___assertEqual(list(b), []) 8 | 9 | # test_sinkstate_tuple 10 | a = (0, 1, 2, 3, 4) 11 | b = iter(a) 12 | ___assertEqual(list(b), list(range(5))) 13 | ___assertEqual(list(b), []) 14 | 15 | # test_sinkstate_string 16 | a = "abcde" 17 | b = iter(a) 18 | ___assertEqual(list(b), ['a', 'b', 'c', 'd', 'e']) 19 | ___assertEqual(list(b), []) 20 | 21 | # test_sinkstate_callable 22 | # This used to fail 23 | def spam(state=[0]): 24 | i = state[0] 25 | state[0] = i+1 26 | if i == 10: 27 | raise AssertionError("shouldn't have gotten this far") 28 | return i 29 | b = iter(spam, 5) 30 | ___assertEqual(list(b), list(range(5))) 31 | ___assertEqual(list(b), []) 32 | 33 | # test_sinkstate_dict 34 | # XXX For a more thorough test, see towards the end of: 35 | # http://mail.python.org/pipermail/python-dev/2002-July/026512.html 36 | a = {1:1, 2:2, 0:0, 4:4, 3:3} 37 | for b in iter(a), a.keys(), a.items(), a.values(): 38 | b = iter(a) 39 | ___assertEqual(len(list(b)), 5) 40 | ___assertEqual(list(b), []) 41 | 42 | # test_sinkstate_range 43 | a = range(5) 44 | b = iter(a) 45 | ___assertEqual(list(b), list(range(5))) 46 | ___assertEqual(list(b), []) 47 | -------------------------------------------------------------------------------- /python-reference/lists/test_list_identity.py: -------------------------------------------------------------------------------- 1 | if(not ([] is not [])): raise Exception('list identity') 2 | -------------------------------------------------------------------------------- /python-reference/lists/test_list_simple.py: -------------------------------------------------------------------------------- 1 | if (not (list([]) == [])): raise Exception('List empty') 2 | l0_3 = [0, 1, 2, 3] 3 | l0_3_bis = list(l0_3) 4 | if (not (l0_3 == l0_3_bis)): raise Exception('List identity') 5 | if (not (l0_3 is not l0_3_bis)): raise Exception('List identity') 6 | if (not (list(()) == [])): raise Exception( 'List tuple') 7 | if (not (list((0, 1, 2, 3)), [0, 1, 2, 3])): raise Exception('List tuple 2') 8 | if (not (list('') == [])): raise Exception( 'List string 1') 9 | if (not (list('spam') == ['s', 'p', 'a', 'm'])): raise Exception( 'List string 2') 10 | 11 | -------------------------------------------------------------------------------- /python-reference/lists/test_list_truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not []) 2 | ___assertTrue([42]) 3 | -------------------------------------------------------------------------------- /python-reference/range/range-errs.py: -------------------------------------------------------------------------------- 1 | ___assertRaises(TypeError, range) 2 | ___assertRaises(TypeError, range, 1, 2, 3, 4) 3 | ___assertRaises(ValueError, range, 1, 2, 0) 4 | 5 | ___assertRaises(TypeError, range, 0.0, 2, 1) 6 | ___assertRaises(TypeError, range, 1, 2.0, 1) 7 | ___assertRaises(TypeError, range, 1, 2, 1.0) 8 | ___assertRaises(TypeError, range, 1e100, 1e101, 1e101) 9 | 10 | ___assertRaises(TypeError, range, 0, "spam") 11 | ___assertRaises(TypeError, range, 0, 42, "spam") 12 | -------------------------------------------------------------------------------- /python-reference/range/range-list.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(list(range(3)), [0, 1, 2]) 2 | ___assertEqual(list(range(1, 5)), [1, 2, 3, 4]) 3 | ___assertEqual(list(range(0)), []) 4 | ___assertEqual(list(range(-3)), []) 5 | ___assertEqual(list(range(1, 10, 3)), [1, 4, 7]) 6 | ___assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) 7 | -------------------------------------------------------------------------------- /python-reference/range/range-vars.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | b = 100 3 | c = 50 4 | 5 | ___assertEqual(list(range(a, a+2)), [a, a+1]) 6 | ___assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) 7 | ___assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) 8 | 9 | seq = list(range(a, b, c)) 10 | ___assertIn(a, seq) 11 | ___assertNotIn(b, seq) 12 | ___assertEqual(len(seq), 2) 13 | 14 | seq = list(range(b, a, -c)) 15 | ___assertIn(b, seq) 16 | ___assertNotIn(a, seq) 17 | ___assertEqual(len(seq), 2) 18 | 19 | seq = list(range(-a, -b, -c)) 20 | ___assertIn(-a, seq) 21 | ___assertNotIn(-b, seq) 22 | ___assertEqual(len(seq), 2) 23 | -------------------------------------------------------------------------------- /python-reference/scope/bound-and-free.py: -------------------------------------------------------------------------------- 1 | # var is bound and free in class 2 | 3 | def f(x): 4 | class C: 5 | def m(self): 6 | return x 7 | a = x 8 | return C 9 | 10 | inst = f(3)() 11 | ___assertEqual(inst.a, inst.m()) 12 | -------------------------------------------------------------------------------- /python-reference/scope/extra-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder2(x): 2 | def extra(): # check freevars passing through non-use scopes 3 | def adder(y): 4 | return x + y 5 | return adder 6 | return extra() 7 | 8 | inc = make_adder2(1) 9 | plus10 = make_adder2(10) 10 | 11 | ___assertEqual(inc(1), 2) 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /python-reference/scope/freevar-in-method.py: -------------------------------------------------------------------------------- 1 | def test(): 2 | method_and_var = "var" 3 | class Test: 4 | def method_and_var(self): 5 | return "method" 6 | def test(self): 7 | return method_and_var 8 | def actual_global(self): 9 | return str("global") 10 | def str(self): 11 | return str(self) 12 | return Test() 13 | 14 | t = test() 15 | ___assertEqual(t.test(), "var") 16 | ___assertEqual(t.method_and_var(), "method") 17 | ___assertEqual(t.actual_global(), "global") 18 | 19 | method_and_var = "var" 20 | class Test: 21 | # this class is not nested, so the rules are different 22 | def method_and_var(self): 23 | return "method" 24 | def test(self): 25 | return method_and_var 26 | def actual_global(self): 27 | return str("global") 28 | def str(self): 29 | return str(self) 30 | 31 | t = Test() 32 | ___assertEqual(t.test(), "var") 33 | ___assertEqual(t.method_and_var(), "method") 34 | ___assertEqual(t.actual_global(), "global") 35 | -------------------------------------------------------------------------------- /python-reference/scope/lambda1.py: -------------------------------------------------------------------------------- 1 | f1 = lambda x: lambda y: x + y 2 | inc = f1(1) 3 | plus10 = f1(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /python-reference/scope/lambda2.py: -------------------------------------------------------------------------------- 1 | f2 = lambda x: (lambda : lambda y: x + y)() 2 | inc = f2(1) 3 | plus10 = f2(10) 4 | ___assertEqual(inc(1), 2) 5 | ___assertEqual(plus10(5), 15) 6 | -------------------------------------------------------------------------------- /python-reference/scope/lambda3.py: -------------------------------------------------------------------------------- 1 | f3 = lambda x: lambda y: global_x + y 2 | global_x = 1 3 | inc = f3(None) 4 | ___assertEqual(inc(2), 3) 5 | -------------------------------------------------------------------------------- /python-reference/scope/lambda4.py: -------------------------------------------------------------------------------- 1 | f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y) 2 | g = f8(1, 2, 3) 3 | h = g(2, 4, 6) 4 | ___assertEqual(h(), 18) 5 | -------------------------------------------------------------------------------- /python-reference/scope/locals-class.py: -------------------------------------------------------------------------------- 1 | # This test verifies that calling locals() does not pollute 2 | # the local namespace of the class with free variables. Old 3 | # versions of Python had a bug, where a free variable being 4 | # passed through a class namespace would be inserted into 5 | # locals() by locals() or exec or a trace function. 6 | # 7 | # The real bug lies in frame code that copies variables 8 | # between fast locals and the locals dict, e.g. when executing 9 | # a trace function. 10 | 11 | def f(x): 12 | class C: 13 | x = 12 14 | def m(self): 15 | return x 16 | locals() 17 | return C 18 | 19 | ___assertEqual(f(1).x, 12) 20 | 21 | def f(x): 22 | class C: 23 | y = x 24 | def m(self): 25 | return x 26 | z = list(locals()) 27 | return C 28 | 29 | varnames = f(1).z 30 | ___assertNotIn("x", varnames) 31 | ___assertIn("y", varnames) 32 | -------------------------------------------------------------------------------- /python-reference/scope/locals-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | def h(z): 4 | return y + z 5 | w = x + y 6 | y += 3 7 | return locals() 8 | return g 9 | 10 | d = f(2)(4) 11 | ___assertIn('h', d) 12 | del d['h'] 13 | ___assertEqual(d, {'x': 2, 'y': 7, 'w': 6}) 14 | -------------------------------------------------------------------------------- /python-reference/scope/mixed-freevars-and-cellvars.py: -------------------------------------------------------------------------------- 1 | def identity(x): 2 | return x 3 | 4 | def f(x, y, z): 5 | def g(a, b, c): 6 | a = a + x # 3 7 | def h(): 8 | # z * (4 + 9) 9 | # 3 * 13 10 | return identity(z * (b + y)) 11 | y = c + z # 9 12 | return h 13 | return g 14 | 15 | g = f(1, 2, 3) 16 | h = g(2, 4, 6) 17 | ___assertEqual(h(), 39) 18 | -------------------------------------------------------------------------------- /python-reference/scope/nearest-enclosing-scope.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(y): 3 | x = 42 # check that this masks binding in f() 4 | def h(z): 5 | return x + z 6 | return h 7 | return g(2) 8 | 9 | test_func = f(10) 10 | ___assertEqual(test_func(5), 47) 11 | -------------------------------------------------------------------------------- /python-reference/scope/nested-nonlocal.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def g(): 3 | nonlocal x 4 | x -= 2 5 | def h(): 6 | nonlocal x 7 | x += 4 8 | return x 9 | return h 10 | return g 11 | 12 | g = f(1) 13 | h = g() 14 | ___assertEqual(h(), 3) 15 | -------------------------------------------------------------------------------- /python-reference/scope/nesting-global-no-free.py: -------------------------------------------------------------------------------- 1 | def make_adder4(): # XXX add exta level of indirection 2 | def nest(): 3 | def nest(): 4 | def adder(y): 5 | return global_x + y # check that plain old globals work 6 | return adder 7 | return nest() 8 | return nest() 9 | 10 | global_x = 1 11 | adder = make_adder4() 12 | ___assertEqual(adder(1), 2) 13 | 14 | global_x = 10 15 | ___assertEqual(adder(-2), 8) 16 | -------------------------------------------------------------------------------- /python-reference/scope/nesting-plus-free-ref-to-global.py: -------------------------------------------------------------------------------- 1 | def make_adder6(x): 2 | global global_nest_x 3 | def adder(y): 4 | return global_nest_x + y 5 | global_nest_x = x 6 | return adder 7 | 8 | inc = make_adder6(1) 9 | plus10 = make_adder6(10) 10 | 11 | ___assertEqual(inc(1), 11) # there's only one global 12 | ___assertEqual(plus10(-2), 8) 13 | -------------------------------------------------------------------------------- /python-reference/scope/nesting-through-class.py: -------------------------------------------------------------------------------- 1 | def make_adder5(x): 2 | class Adder: 3 | def __call__(self, y): 4 | return x + y 5 | return Adder() 6 | 7 | inc = make_adder5(1) 8 | plus10 = make_adder5(10) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /python-reference/scope/nonlocal-class.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | nonlocal x 4 | x += 1 5 | def get(self): 6 | return x 7 | return c() 8 | 9 | c = f(0) 10 | ___assertEqual(c.get(), 1) 11 | ___assertNotIn("x", c.__class__.__dict__) 12 | -------------------------------------------------------------------------------- /python-reference/scope/nonlocal-function.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def inc(): 3 | nonlocal x 4 | x += 1 5 | return x 6 | def dec(): 7 | nonlocal x 8 | x -= 1 9 | return x 10 | return inc, dec 11 | 12 | inc, dec = f(0) 13 | ___assertEqual(inc(), 1) 14 | ___assertEqual(inc(), 2) 15 | ___assertEqual(dec(), 1) 16 | ___assertEqual(dec(), 0) 17 | -------------------------------------------------------------------------------- /python-reference/scope/nonlocal-method.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | class c: 3 | def inc(self): 4 | nonlocal x 5 | x += 1 6 | return x 7 | def dec(self): 8 | nonlocal x 9 | x -= 1 10 | return x 11 | return c() 12 | c = f(0) 13 | ___assertEqual(c.inc(), 1) 14 | ___assertEqual(c.inc(), 2) 15 | ___assertEqual(c.dec(), 1) 16 | ___assertEqual(c.dec(), 0) 17 | -------------------------------------------------------------------------------- /python-reference/scope/recursion.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | def fact(n): 3 | if n == 0: 4 | return 1 5 | else: 6 | return n * fact(n - 1) 7 | if x >= 0: 8 | return fact(x) 9 | else: 10 | raise ValueError("x must be >= 0") 11 | 12 | ___assertEqual(f(6), 720) 13 | -------------------------------------------------------------------------------- /python-reference/scope/simple-and-rebinding.py: -------------------------------------------------------------------------------- 1 | def make_adder3(x): 2 | def adder(y): 3 | return x + y 4 | x = x + 1 # check tracking of assignment to x in defining scope 5 | return adder 6 | 7 | inc = make_adder3(0) 8 | plus10 = make_adder3(9) 9 | 10 | ___assertEqual(inc(1), 2) 11 | ___assertEqual(plus10(-2), 8) 12 | -------------------------------------------------------------------------------- /python-reference/scope/simple-nesting.py: -------------------------------------------------------------------------------- 1 | def make_adder(x): 2 | def adder(y): 3 | return x + y 4 | return adder 5 | 6 | inc = make_adder(1) 7 | plus10 = make_adder(10) 8 | 9 | ___assertEqual(inc(1), 2) 10 | ___assertEqual(plus10(-2), 8) 11 | -------------------------------------------------------------------------------- /python-reference/scope/unbound-local.py: -------------------------------------------------------------------------------- 1 | def errorInOuter(): 2 | print(y) 3 | def inner(): 4 | return y 5 | y = 1 6 | 7 | def errorInInner(): 8 | def inner(): 9 | return y 10 | inner() 11 | y = 1 12 | 13 | ___assertRaises(UnboundLocalError, errorInOuter) 14 | ___assertRaises(NameError, errorInInner) 15 | -------------------------------------------------------------------------------- /python-reference/super/test-super.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def f(self): 3 | return 'A' 4 | @classmethod 5 | def cm(cls): 6 | return (cls, 'A') 7 | 8 | class B(A): 9 | def f(self): 10 | return super().f() + 'B' 11 | @classmethod 12 | def cm(cls): 13 | return (cls, super().cm(), 'B') 14 | 15 | class C(A): 16 | def f(self): 17 | return super().f() + 'C' 18 | @classmethod 19 | def cm(cls): 20 | return (cls, super().cm(), 'C') 21 | 22 | class G(A): 23 | pass 24 | 25 | ___assertEqual(A.cm(), (A, 'A')) 26 | ___assertEqual(A().cm(), (A, 'A')) 27 | ___assertEqual(G.cm(), (G, 'A')) 28 | ___assertEqual(G().cm(), (G, 'A')) 29 | 30 | # Issue4360: super() did not work in a function that 31 | # contains a closure 32 | class EE(A): 33 | def f(self): 34 | def nested(): 35 | self 36 | return super().f() + 'E' 37 | 38 | ___assertEqual(EE().f(), 'AE') 39 | -------------------------------------------------------------------------------- /python-reference/tuple/tuple-add.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u += (2, 3) 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /python-reference/tuple/tuple-constructors.py: -------------------------------------------------------------------------------- 1 | # calling built-in types without argument must return empty 2 | ___assertEqual(tuple(), ()) 3 | t0_3 = (0, 1, 2, 3) 4 | t0_3_bis = tuple(t0_3) 5 | ___assertTrue(t0_3 is t0_3_bis) 6 | ___assertEqual(tuple([]), ()) 7 | ___assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) 8 | ___assertEqual(tuple(''), ()) 9 | ___assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) 10 | -------------------------------------------------------------------------------- /python-reference/tuple/tuple-length.py: -------------------------------------------------------------------------------- 1 | ___assertEqual(len(()), 0) 2 | ___assertEqual(len((0,)), 1) 3 | ___assertEqual(len((0, 1, 2)), 3) 4 | -------------------------------------------------------------------------------- /python-reference/tuple/tuple-mul.py: -------------------------------------------------------------------------------- 1 | u = (0, 1) 2 | u2 = u 3 | u *= 3 4 | ___assertTrue(u is not u2) 5 | -------------------------------------------------------------------------------- /python-reference/tuple/tuple-truth.py: -------------------------------------------------------------------------------- 1 | ___assertTrue(not ()) 2 | ___assertTrue((42, )) 3 | -------------------------------------------------------------------------------- /python-reference/types/test_booleans.py: -------------------------------------------------------------------------------- 1 | if 0 or 0: raise Exception('0 or 0 is true instead of false') 2 | if 1 and 1: pass 3 | else: raise Exception('1 and 1 is false instead of true') 4 | if not 1: raise Exception('not 1 is true instead of false') 5 | -------------------------------------------------------------------------------- /python-reference/types/test_comparisons.py: -------------------------------------------------------------------------------- 1 | if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass 2 | else: raise Exception('int comparisons failed') 3 | if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass 4 | else: raise Exception('float comparisons failed') 5 | if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass 6 | else: raise Exception('string comparisons failed') 7 | if None is None: pass 8 | else: raise Exception('identity test failed') 9 | -------------------------------------------------------------------------------- /python-reference/types/test_div_zero.py: -------------------------------------------------------------------------------- 1 | try: 5.0 / 0.0 2 | except ZeroDivisionError: pass 3 | else: raise Exception("5.0 / 0.0 didn't raise ZeroDivisionError") 4 | 5 | try: 5.0 // 0.0 6 | except ZeroDivisionError: pass 7 | else: raise Exception("5.0 // 0.0 didn't raise ZeroDivisionError") 8 | 9 | try: 5.0 % 0.0 10 | except ZeroDivisionError: pass 11 | else: raise Exception("5.0 % 0.0 didn't raise ZeroDivisionError") 12 | 13 | try: 5 / 0 14 | except ZeroDivisionError: pass 15 | else: raise Exception("5 / 0 didn't raise ZeroDivisionError") 16 | 17 | try: 5 // 0 18 | except ZeroDivisionError: pass 19 | else: raise Exception("5 // 0 didn't raise ZeroDivisionError") 20 | 21 | try: 5 % 0 22 | except ZeroDivisionError: pass 23 | else: raise Exception("5 % 0 didn't raise ZeroDivisionError") 24 | 25 | -------------------------------------------------------------------------------- /python-reference/types/test_floats.py: -------------------------------------------------------------------------------- 1 | if 12.0 + 24.0 != 36.0: raise Exception('float op +') 2 | if 12.0 + (-24.0) != -12.0: raise Exception('float op +/-') 3 | if (-12.0) + 24.0 != 12.0: raise Exception('float op -/+') 4 | if (-12.0) + (-24.0) != -36.0: raise Exception('float op -/+/-') 5 | if not 12.0 < 24.0: raise Exception('float op <') 6 | if not -24.0 < -12.0: raise Exception('float op < negative') 7 | -------------------------------------------------------------------------------- /python-reference/types/test_simple_string_ops.py: -------------------------------------------------------------------------------- 1 | if 'xyz' + 'abcde' != 'xyzabcde': raise Exception('string concatenation') 2 | if 'xyz'*3 != 'xyzxyzxyz': raise Exception('string repetition *3') 3 | if 0*'abcde' != '': raise Exception('string repetition 0*') 4 | if min('abc') != 'a' or max('abc') != 'c': raise Exception('min/max string') 5 | if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass 6 | else: raise Exception('in/not in string') 7 | -------------------------------------------------------------------------------- /python-reference/types/test_simple_strings.py: -------------------------------------------------------------------------------- 1 | if len('') != 0: raise Exception('len(\'\')') 2 | if len('a') != 1: raise Exception('len(\'a\')') 3 | if len('abcdef') != 6: raise Exception('len(\'abcdef\')') 4 | -------------------------------------------------------------------------------- /python-reference/types/test_string_slices.py: -------------------------------------------------------------------------------- 1 | a = '0123456789' 2 | if (not (a[::] == a)): raise Exception('Slice total') 3 | if (not (a[::2] == '02468')): raise Exception('Slice 2') 4 | if (not (a[1::2] == '13579')): raise Exception('Slice 1::2') 5 | if (not (a[::-1] =='9876543210')): raise Exception('Slice ::-1') 6 | if (not (a[::-2] == '97531')): raise Exception('Slice ::-2') 7 | if (not (a[3::-2] == '31')): raise Exception('Slice 3::-2') 8 | if (not (a[-100:100:] == a)): raise Exception('Slice -100::100') 9 | if (not (a[100:-100:-1] == a[::-1])): raise Exception('Slice triple') 10 | if (not (a[-100:100:2] == '02468')): raise Exception('Slice triple 2') 11 | -------------------------------------------------------------------------------- /python-reference/types/types_truthy1.py: -------------------------------------------------------------------------------- 1 | if None: raise Exception('None is true instead of false') 2 | if 0: raise Exception('0 is true instead of false') 3 | if 0.0: raise Exception('0.0 is true instead of false') 4 | if '': raise Exception('\'\' is true instead of false') 5 | if not 1: raise Exception('1 is false instead of true') 6 | if not 1.0: raise Exception('1.0 is false instead of true') 7 | if not 'x': raise Exception('\'x\' is false instead of true') 8 | if not {'x': 1}: raise Exception('{\'x\': 1} is false instead of true') 9 | -------------------------------------------------------------------------------- /python-reference/types/types_truthy2.py: -------------------------------------------------------------------------------- 1 | def f(): pass 2 | class C: pass 3 | x = C() 4 | if not f: raise Exception('f is false instead of true') 5 | if not C: raise Exception('C is false instead of true') 6 | if not x: raise Exception('x is false instead of true') 7 | -------------------------------------------------------------------------------- /python-syntax.rkt: -------------------------------------------------------------------------------- 1 | #lang plai-typed 2 | 3 | (define-type PyExpr 4 | [PySeq (es : (listof PyExpr))] 5 | [PyNum (n : number)] 6 | [PyId (x : symbol)] 7 | [PyApp (fun : PyExpr) (args : (listof PyExpr))]) 8 | 9 | --------------------------------------------------------------------------------