Saturday 10:50 a.m.–11:20 a.m.
Investigating Python Wats
- Audience level:
- Python Core (language, stdlib, etc.)
Many of us have experienced a "wat" in Python - some behavior that totally mystifies us. We'll look at three areas where wats arise - identity, mutability, and scope. For each of these three topics, we'll look at some common surprising behaviors, investigate the cause of the behaviors, and cover some practical tips on how to avoid related bugs.
## Identity First, we'll look at some common CPython gotchas involving object identity. We'll try to guess the value of various `is` statements, and then see what the actual value is. Then, we'll discuss why some of these statements evaluate to `True` and others `False`, and how object identity differs from equality. We'll discuss some implementation details of CPython, and how they lead to `is` evaluating differently for integers between -5 and 256 and integers outside that range. Finally, we'll cover some quick practical tips about how to avoid bugs resulting from using the `is` statement. ## Mutability Again, we'll look at some common Python gotchas, this time caused by mutability. Then, we'll investigate which common Python objects are mutable and which aren't, which operations mutate Python objects, and what happens when you mutate an object. In the case of mutable default arguments, we'll even see how we can mutate the default argument from outside the function body using some internals that Python exposes to us. We'll end this section by discussing some practical tips on how to avoid bugs due to mutability, how to make real copies, and a common alternative to using mutable default arguments. ## Scope First we'll see some examples of Python name resolution, and we'll try to guess what object the name is bound to, if any, with some surprising results. After seeing some examples, we'll investigate how the Python interpreter does name resolution, and we'll explore the meaning of the cryptic `UnboundLocalError`.