Skip to main content

Posts

Showing posts from October, 2021

How to use function closure to capture common arguments in python

Sometimes you need a function that already 'captures' some information you don't want to repeat when calling it. For example, logging may require you to pass in a lot of contextual information for each call. Instead you can capture the common/unchanging contextual information in a function (using its clsoosure) then call the resulting function with less args (only those that are changing in each call site)   class AClass:   def __init__(self):     self.make_log_msg = lambda m: f"a={self.a}, b={self.b}, message={m}"  def do_something(self):     doStuff();     logger.info(self.make_log_msg('test message')) In the absence of the make_log_msg() function you would need to pass all of a,b,c into every logging function call as in self.make_log_msg(self.a, self.b, message) .  This is possible because make_log_msg returns a function (lambda function in this case) that already captures the values self.a and self.b in its closure at the time of creation. Note that th