Python Power Tools <ul>I had my power drill slung low on my toolbelt and I said,“Go ahead, honey. Break something.” - Tim Allen on the challenges of figuring out what to do with a new set of general-purpose tools </ul>
Tips & Tricks Often you need one little piece of information, and no one is to blame it's not there. Some things just... need some help
Setting the Name of a Function If an outer function just returns an inner function (often a closure), the name of the returned function object is fixed, which can be confusing when the name is shown during introspection or debugging: >>> def make_adder(addend): … def adder(augend): return augend+addend … return adder … >>> plus100 = make_adder(100) >>> plus_23 = make_adder(23) >>> print plus100(1000), plus_23(1000) 1100 1023 >>> print plus100, plus_23 <function adder at 0x386530> <function adder at 0x3825f0>
Python 2.4+ You can solve the problem by setting the __name_ attribute of the inner function before returning it: def make_adder(addend): def adder(augend): return augend+addend adder._name__ = 'add_%s' % (addend, ) With this change the output becomes more useful: >>> print plus100, plus_23 <function add_100 at 0x386530> <function add_23 at 0x3825f0>
Python 2.3 Unfortunately, the __name__ attribute is read-only in this release. The same effect is achieved by constructing a new function object which differs from the other only in name: import new def make_adder(addend): def adder(augend): return augend+addend return new.function( adder.func_code, adder.func_globals, 'add_%s' % (addend,), adder.func_defaults, adder.func_closure )
A particular slide catching your eye?
Clipping is a handy way to collect important slides you want to go back to later.