56. 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
57. 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>
58. 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>
59. 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 )