Skip to main content

Posts

Showing posts with the label Python

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 t...

Remote debugging of python code in Visual Studio Code

Remote debugging with python and visual studio Code In terminal install debugpy into your environment with something like     python -m pip install debugpy Create a visual studio launch configuration and add following to it following (or just use vs code create configuraiton button to easily create it choose type Python and select from the list, 'Remote attach') { "name" : "Python: Remote Attach" , "type" : "python" , "request" : "attach" , "port" : 5678 , "host" : "localhost" , "pathMappings" : [{ "localRoot" : "${workspaceFolder}" , "remoteRoot" : "." }] }, Run this in the command line to start a debugging server with your script runner python3 -m debugpy --listen 1.2.3.4:5678 --wait-for-client Yourscript.py Now run the launch configuration from vs code to attach to this debugger

My first encounter with Lambda functions in Python

Lambda functions in Python Here is a very simple  lambda function , this example is one of creating a polynomial function with given coefficients, and storing that as a lambda function in a variable 'f' that can now be used as a function, cool! # This returns a function that represents a polynomial # Input is a dictionary with a,b,c being required keys def polyf(**coeffs): """Returns a lambda function""" return lambda x: coeffs['a']*x*x + coeffs['b']*x+coeffs['c'] # now returns a lambda function that will evaluate 2nd order polynomial with coeffs a, b, c when called f = polyf(a=1,b=2,c=3) print "Help doc for this function = ", polyf.__doc__ # Try using that lambda function now, Done! print f(0.1) print f(0)