2022-01-15_loving-the-lambda.html


001| #:name::Loving the Lambda
002| #:link::https://thehardcorecoder.com/2022/01/15/loving-the-lambda/
003| #:date::2022-01-15
004| #:code::
005| # Using KWARGS allows passing lots of parameters to a function.
006| # It keeps the function signature very clean, but gives up the
007| # self-documenting of formal parameter names. It also allows
008| # unknown parameters, but this can be a feature if you pass
009| # KWARGS to multiple or sub functions. As always, it's choice.
010| #
011| def interesting_function (**kwargs):
012|     '''My interesting function needs many parameters!'''
013|     xdim = int(kwargs['xdim']) if 'xdim' in kwargs else 300
014|     ydim = int(kwargs['ydim']) if 'ydim' in kwargs else 300
015|     xmin = float(kwargs['xmin']) if 'xmin' in kwargs else -5.0
016|     xmax = float(kwargs['xmax']) if 'xmax' in kwargs else +5.0
017|     ymin = float(kwargs['ymin']) if 'ymin' in kwargs else  0.0
018|     ymax = float(kwargs['ymax']) if 'ymax' in kwargs else +1.0
019|     xaxis = kwargs['xaxis'] if 'xaxis' in kwargs else 'Months'
020|     yaxis = kwargs['yaxis'] if 'yaxis' in kwargs else 'Trains'
021|     #
022|     # ...interesting stuff...
023|     #
024| 
025| def interesting_class (object):
026|     def __init__ (self, **kwargs):
027|         '''My interesting object has lots of options!'''
028|         xdim = int(kwargs['xdim']) if 'xdim' in kwargs else 300
029|         ydim = int(kwargs['ydim']) if 'ydim' in kwargs else 300
030|         #
031|         # ...etc...
032|         #
033| 
034| #:code::
035| # KWARG macro takes a parameter name, default value, and a
036| # set of keyword/values (a dict or similar duck). If the
037| # parameter exists in the dict, the function returns its
038| # value, otherwise it returns the default value.
039| #
040| KWARG = lambda name,dflt,args:args[name] if name in args else dflt
041| 
042| # This saves typing and eliminates a bug opportunity:
043| def interesting_function (**kwargs):
044|     '''My interesting function needs many parameters!'''
045|     xdim = int(KWARG('xdim',300,kwargs))
046|     ydim = int(KWARG('ydim',300,kwargs))
047|     xmin = float(KWARG('xmin',-5.0,kwargs))
048|     xmax = float(KWARG('xmax',+5.0,kwargs))
049|     ymin = float(KWARG('ymin', 0.0,kwargs))
050|     ymax = float(KWARG('ymax',+1.0,kwargs))
051|     xaxis = KWARG('xaxis','Months',kwargs)
052|     yaxis = KWARG('yaxis','Trains',kwargs)
053|     #
054|     # ...interesting stuff...
055|     #
056| 
057| def interesting_class (object):
058|     def __init__ (self, **kwargs):
059|         '''My interesting object has lots of options!'''
060|         xdim = int(KWARG('xdim',300,kwargs))
061|         ydim = int(KWARG('ydim',300,kwargs))
062|         #
063|         # ...etc...
064|         #
065| 
066| #:code::
067| # KWARG macro takes a parameter name, default value, and set
068| # of keyword/values (a dict or similar duck). If the parameter
069| # exists in the dict, the function returns its value. If not,
070| # it returns the default value.
071| #
072| KWARG = lambda nam,val,typ,kws: typ(kws[nam]) if nam in kws else val
073| 
074| # This saves typing and eliminates a bug opportunity:
075| def interesting_function (**kwargs):
076|     '''My interesting function needs many parameters!'''
077|     xdim = KWARG('xdim',300,int,kwargs)
078|     ydim = KWARG('ydim',300,int,kwargs)
079|     xmin = KWARG('xmin',-5.0,float,kwargs)
080|     xmax = KWARG('xmax',+5.0,float,kwargs)
081|     ymin = KWARG('ymin', 0.0,float,kwargs)
082|     ymax = KWARG('ymax',+1.0,float,kwargs)
083|     xaxis = KWARG('xaxis','Months',str,kwargs)
084|     yaxis = KWARG('yaxis','Trains',str,kwargs)
085|     #
086|     # ...interesting stuff...
087|     #
088| 
089| def interesting_class (object):
090|     def __init__ (self, **kwargs):
091|         '''My interesting object has lots of options!'''
092|         xdim = KWARG('xdim',300,int,kwargs)
093|         ydim = KWARG('ydim',300,int,kwargs)
094|         #
095|         # ...etc...
096|         #
097| 
098| #:code::
099| # Fun with types...
100| 
101| def range_factory (typ=int):
102|     def _range (*args):
103|         for x in range(*args):
104|             yield typ(x)
105|     return _range
106| 
107| ri = range_factory()
108| 
109| print( [n for n in ri(4)] )
110| print( [n for n in ri(8)] )
111| print( [n for n in ri(12)] )
112| print()
113| 
114| rf = range_factory(float)
115| 
116| print( [n for n in rf(4)] )
117| print( [n for n in rf(8)] )
118| print( [n for n in rf(12)] )
119| print()
120| 
121| rs = range_factory(str)
122| 
123| print( [n for n in rs(4)] )
124| print( [n for n in rs(8)] )
125| print( [n for n in rs(12)] )
126| print()
127| 
128| #:code::
129| '''An "s" unless n=1.'''
130| plural = lambda n: '' if n == 1 else 's'
131| 
132| '''Turn a list into a string.'''
133| lst2str = lambda lst: ''.join([str(x) for x in lst])
134| lst2str2 = lambda lst,delim: delim.join([str(x) for x in lst])
135| 
136| '''Pretty Print a complex number.'''
137| zstr = lambda z: ('(%+.5f, %+.5fi)' % (z.real,z.imag))
138| 
139| '''Return an object's typename.'''
140| typename = lambda obj: type(obj).__name__
141| 
142| '''Compare two numerical values.'''
143| comp = lambda a,b: ((b < a) - (a < b))
144| 
145| '''Fraction.'''
146| frac = lambda a,b: (float(a) / float(b)) if b else 0.0
147| 
148| '''Return a Pythagorean distance on a vector of coordinates.'''
149| distance = lambda ds: sqrt(sum([float(d)*float(d) for d in ds]))
150| 
151| '''Return the dot product of two vectors.'''
152| dot_product = lambda a,b: sum([float(x)*float(y) for x,y in zip(a,b)])
153| 
154| #:code::
155| records = Query(query_parameters)
156| 
157| n = len(records)
158| s = plural(records)
159| print('Found %d record%s' % (n,s))
160| 
161| #:code::
162| Factorial = lambda n: 1 if n<1 else n*Factorial(n-1)
163| 
164| Collatz_nbr = lambda n: ((n*3)+1) if (n % 2) else (n//2)
165| 
166| Collatz_seq = lambda n: [n] if (n in [-1,0,+1])
167|                             else [n]+Collatz_seq(Collatz_nbr(n))
168| 
169| #:end:code::
170|