Lecture 6 Functional Abstraction
- Questions
- slide 8, intrinsic name square question
- how to know what is a runtime error vs syntax error
-
Decorators
@trace def square(x): return x*x """ Defining trace ourself """ def trace1(fn): fn = <function with 1 arg> def traced(x): print("Calling", fn, "on argument", x) return fn(x) return traced
- Writing @trace
- Breaking down every function call
- Telling us the input and output
- Each time we call a function, tells us what we are calling the function on
- Way to transform a function into another function
- Decorator has to take in a function and return a function
- Overrides the current function
- printing value first, then applying the function
- Return
- Return Statements
- completes the evaluation of a call expression and provides it value
- switch back to previous environment, f(x) now has a value
- Only one return statement is ever executed while executing body of function
- Abstraction
- Square has the intrinsic name sqare (not needed)
- Names don’t matter for correctness, but matter a lot for composition
- best documented in docstring
- Function names typically convey their affect, behavior, value returned
- Which Values Deserve a Name
- reasons to add a new name
- repeated compound expression
- Meaningful parts of complex expressions
- reasons to add a new name
- Errors and Tracebacks
- Syntax Errors
- Detected by the Python interpreter before program executes
- Rules about form, parentheses
- Runtime Errors
- Detected while running
- Logic and Behavior Errors
- Not detected by Python interpreter
- Program doesn’t crash, but gives wrong output
- This is why we use tests
- Common Bugs from Students
- NameError
- spelling
- SyntaxError
- Missing parenthesis
- Logic and Behavior Errors
- = vs ==
- Off by 1 errors
- IndentationError
- Type Error
- invalid types for an operator
- using non-function objects in a function call
- passing incorrect number of arguments to a function
- IndexError
- Index sequence with a # that exceeds size of sequence
- NameError
- Debugging
- To run the doctest above
- python3 -m doctest
.py - nothing is displayed when doctest passed
- You should test edge cases
- When running debug
- put a variable debug and you can toggle prints when debugging
- assert
- assert isinstance(x, int), “the input of x has to be an int”
- Use print(’DEBUG:’) for okpy
- Implementing Functions
- Write about what you know about the problem
- Read the description
- Look at the examples
- Read the template
- you may be able to change your own solution into the template 2.
- Writing @trace