Function dissection lab -- learn how functions
summary
Asserts that Python treats functions as objects and demonstrates the mechanics: inspect __code__ and its fields (co_argcount, co_varnames, co_flags, co_consts), __defaults__, and closure slots; uses the dis module and Python Tutor to use dis to inspect bytecode and to trace frames; shows the surprising mutable-default bug where a list in __defaults__ mutable defaults persist across calls; reproduces scoping behaviors (unbound local, global, nonlocal) with live demos that all execute as described.
AI-written summary · about
chapters (25)
- 0:00Intro
- 0:22I teach Python
- 1:06Consider this code
- 1:50Function objects? . When you use def. you create a function object.
- 3:34Example
- 6:51Error messages use this info
- 7:25Additional variables
- 8:52So, how does Python know?
- 10:43Same goes for **kwargs
- 11:08dis.show_code
- 12:10Constants?
- 14:23When Python calls a function...
- 15:04Consider this function
- 15:47Let's add a default
- 17:18Keyword-only arguments
- 17:57Where does Python put that?
- 18:41Let's talk about scoping
- 20:03How does Python know x isn't local?
- 20:24Let's make things more complex
- 22:50A more common version of this problem
- 23:29The "global" declaration
- 24:14Bytecodes with a local"X"
- 24:41Putting the "E" in LEGB
- 27:14What have we learned?
- 27:48Questions or comments?
related talks
26mWhat not to do, and how to do it
22mLow Level Python a Deep dive into the python sources
31mDon't Do This
27mVariables and objects in Python: it's pointers all the way down
01h 18mPython 103: Mmmm... Understanding Python's Memory Model, Mutability, and Methods
02h 43mFunctional Python
50mExploring CPython's bytecode
19mObjects and classes in Python (and JavaScript)
