Ravings about Programming and Philosophy
This example is actually the most useful, but it's also the most boring, so I kept it for last. It's a handy decorator to trace function execution, which is especially useful in catching Heisenbugs in production.
Taming Class Scopes
OK, That's a weird one, but it's actually quite handy: say you're using classes for configurations, and want to nest them like so: ```python class config: root = '/app/' class log: path = root + 'log.txt' ``` Turns out that for some obscure reason, scoping doesn't work the way you'd expect it to when it comes to classes: this code ``NameError``s because ``name 'root' is not defined``. Unless...
Taming Class Attributes
Once upon a time, we needed ordered class attributes. That is, given: ```python class A: x = 1 y = 2 z = 3 ``` We needed ``['x', 'y', 'z']``. "That's easy!" you exclaim; and indeed it is, in Python 3.6. "Well, it was possible before that, too!" you retaliate; and indeed it was, since Python 3.0. But what about *before* that? Can you make this code work in Python 2.7? ```python @ordered() class A: x = 1 y = 2 z = 3 assert A._order == ['x', 'y', 'z'] ```
Do you ever miss the way we used to write C-style enums in the good old days? Yeah, neither do I. But what if I told you this is valid Python code: ```python @cenum() class A: a b c = 10 d assert A.a == 0 assert A.b == 1 assert A.c == 10 assert A.d == 11 ```
The tracer is a wicked cool Python feature that's often overlooked, because it's so... well, wicked. In this series, we learn to use it (which takes about 12 seconds), and then do some really crazy stuff with it.