Sometimes I find myself wanting to run the same code from a few different spots in the same function. Say I have some function func1, and I want to do the same thing from a few different spots in func1. Normally the way to do this would be to write another function, call it "func2", and call func2 from several different places in func1. But what about when it's convenient to have func2 access variables that are local to func1? I find myself writing a closure. Here's a contrived example:
import random
import string
def func1 (param1, param2):
def func2(foo, bar):
print "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)
a = random.randrange(10)
b = ''.join(random.choice(string.letters) for i in xrange(10))
c = random.gauss(0, 1)
if param1:
func2(a*c, param1)
else:
if param2 > 0:
func2(param2, param2)
Is this the Pythonic way to handle this problem? A closure feels like pretty heavy machinery to be rolling out here, especially given that I have to construct a new function every time func1 is called, even though that function is going to be basically the same every time. But it does avoid the duplicated code and in practice the overhead of repeatedly creating func2 doesn't matter to me.