2024-07-22_simple-python-tricks-7.html


001| #:name::Simple Python Tricks #7
002| #:link::https://thehardcorecoder.com/2024/07/22/simple-python-tricks-7/
003| #:date::2024-07-22
004| #:code::
005| def plot_data (*data, **kwargs):
006|     title  = str(kwargs['title']) if 'title' in kwargs else 'A Chart'
007|     ...
008| 
009| plot_data(title='A Chart', size=12)
010| 
011| #:code::
012| '''Return a keyword argument or a default if keyword not found.'''
013| KWARG = lambda nam,dflt,ty,va: ty(va[nam]) if nam in va else dflt
014| 
015| #:code::
016| from examples import KWARG
017| 
018| def plot_data (*args, **kwargs):
019|     '''Data plotting function.'''
020| 
021|     title  = KWARG('title' , 'A Chart', str, kwargs)
022|     size   = KWARG('size'  ,  8  , int, kwargs)
023|     ymax   = KWARG('ymax'  , 10.0, float, kwargs)
024|     yticks = KWARG('yticks',  1.0, float, kwargs)
025|     ...
026|     print(f'{title = }')
027|     print(f'{size = }')
028|     print(f'{ymax = }')
029|     print(f'{yticks = }')
030|     print()
031| 
032| data1 = [1, 2, 3, 4, 5]
033| data2 = [9, 8, 7, 6, 5]
034| plot_data(data1, data2, title='My Data', size=12, ymax=100)
035| 
036| #:code::
037| class ParamsBase:
038|     '''Function parameters object base class.'''
039|     KeyWords = {} # subclass must override!
040| 
041|     def __init__ (self, **kwargs):
042|         assert 0 < len(self.KeyWords)
043|         self._params = kwargs
044| 
045|         # Turn valid arguments into attributes...
046|         # For each keyword in kwargs...
047|         for kw in kwargs:
048|             # If it's not a known keyword...
049|             if kw not in self.KeyWords:
050|                 # Raise an exception...
051|                 raise ValueError(f'Argument unknown: "{kw}"')
052| 
053|             # Get the keyword data type...
054|             datatype,_,_ = self.KeyWords[kw]
055| 
056|             # Create an attribute for the keyword and argument...
057|             setattr(self, kw, datatype(kwargs[kw]))
058| 
059|         # Turn missing parameters into attributes (w/ defaults)...
060|         # For each keyword in kwargs...
061|         for kw in self.KeyWords:
062|             # If we haven't created an attribute yet...
063|             if not hasattr(self, kw):
064| 
065|                 # Get the keyword default value...
066|                 _,default,req = self.KeyWords[kw]
067|                 if req:
068|                     raise ValueError(f'Argument missing: "{kw}"')
069| 
070|                 # Create an attribute for the argument...
071|                 setattr(self, kw, default)
072| 
073| #:code::
074| from examples import ParamsBase
075| 
076| class MyParams (ParamsBase):
077|     KeyWords = {
078|         'title':  (str,'<untitled>', True),
079|         'size':   (int, 5, False),
080|         'xmin':   (float, 0.0, False),
081|         'xmax':   (float, 100.0, True),
082|         'ymin':   (float, 0.0, False),
083|         'ymax':   (float, 100.0, True),
084|         'xticks': (int, 10, False),
085|         'yticks': (int, 10, False),
086|     }
087| 
088| def plot_data (*args, **kwargs):
089|     '''Data plotting function.'''
090| 
091|     ps = MyParams(**kwargs)
092|     ...
093|     print(f'Chart: "{ps.title}" (size {ps.size})')
094|     print(f'X-Axis: {ps.xmin:+.2f} x {ps.xmax:+.2f} (ticks={ps.xticks})')
095|     print(f'Y-Axis: {ps.ymin:+.2f} x {ps.ymax:+.2f} (ticks={ps.yticks})')
096|     print()
097|     ...
098| 
099| plot_data(title='My Data',size=9, xmin=-1,xmax=1, ymin=-1,ymax=1)
100| 
101| #:code::
102| class ParamsBase:
103|     '''Function parameters object base class.'''
104|     KeyWords = {} # subclass must override!
105| 
106|     def __init__ (self, **kwargs):
107|         assert 0 < len(self.KeyWords)
108|         self._params = kwargs
109|         self.extras = {}
110| 
111|         # Turn valid arguments into attributes...
112|         # For each keyword in kwargs...
113|         for kw in kwargs:
114|             # If it's not a known keyword...
115|             if kw not in self.KeyWords:
116|                 # Stash unexpected arguments in extras...
117|                 self.extras[kw] = kwargs[kw]
118|                 continue
119| 
120|             # Get the keyword data type...
121|             datatype,_,_ = self.KeyWords[kw]
122| 
123|             # Create an attribute for the keyword and argument...
124|             setattr(self, kw, datatype(kwargs[kw]))
125| 
126|         # Turn missing parameters into attributes (w/ defaults)...
127|         # For each keyword in kwargs...
128|         for kw in self.KeyWords:
129|             # If we haven't created an attribute yet...
130|             if not hasattr(self, kw):
131| 
132|                 # Get the keyword default value...
133|                 _,default,req = self.KeyWords[kw]
134|                 if req:
135|                     raise ValueError(f'Argument missing: "{kw}"')
136| 
137|                 # Create an attribute for the argument...
138|                 setattr(self, kw, default)
139| 
140| #:code::
141| from examples import ParamsBase
142| 
143| class MyParams (ParamsBase):
144|     KeyWords = {
145|         'title':  (str,'<untitled>', True),
146|         'size':   (int, 5, False),
147|         'xmin':   (float, 0.0, False),
148|         'xmax':   (float, 100.0, True),
149|         'ymin':   (float, 0.0, False),
150|         'ymax':   (float, 100.0, True),
151|         'xticks': (int, 10, False),
152|         'yticks': (int, 10, False),
153|     }
154| 
155| def plot_data (*args, **kwargs):
156|     '''Data plotting function.'''
157| 
158|     ps = MyParams(**kwargs)
159|     assert len(ps.extras)==0, ValueError('Unexpected arguments!')
160|     ...
161|     print(f'Chart: "{ps.title}" (size {ps.size})')
162|     print(f'X-Axis: {ps.xmin:+.2f} x {ps.xmax:+.2f} (ticks={ps.xticks})')
163|     print(f'Y-Axis: {ps.ymin:+.2f} x {ps.ymax:+.2f} (ticks={ps.yticks})')
164|     print()
165|     ...
166| 
167| #:code::
168| from examples import ParamsBase
169| 
170| def plot_data (*args, **kwargs):
171|     '''Data plotting function.'''
172| 
173|     class params (ParamsBase):
174|         KeyWords = {
175|             'title':  (str,'<untitled>', True),
176|             'size':   (int, 5, False),
177|             'xmin':   (float, 0.0, False),
178|             'xmax':   (float, 100.0, True),
179|             'ymin':   (float, 0.0, False),
180|             'ymax':   (float, 100.0, True),
181|             'xticks': (int, 10, False),
182|             'yticks': (int, 10, False),
183|         }
184| 
185|     ps = params(**kwargs)
186|     assert len(ps.extras)==0, ValueError('Unexpected arguments!')
187|     ...
188|     print(f'Chart: "{ps.title}" (size {ps.size})')
189|     print(f'X-Axis: {ps.xmin:+.2f} x {ps.xmax:+.2f} (ticks={ps.xticks})')
190|     print(f'Y-Axis: {ps.ymin:+.2f} x {ps.ymax:+.2f} (ticks={ps.yticks})')
191|     print()
192|     ...
193| 
194| #:code::
195| def vector_object (*args):
196|     x = float(args[0]) if 0 < len(args) else 0.0
197|     y = float(args[1]) if 1 < len(args) else 0.0
198|     z = float(args[2]) if 2 < len(args) else 0.0
199| 
200|     return (x,y,z)
201| 
202| #:code::
203| # Return indexed argument from list or default if list too short.
204| ARG = lambda ix,dflt,ty,va: (ty(va[ix]) if ix < len(va) else dflt)
205| 
206| #:code::
207| from examples import ARG
208| 
209| def vector_object (*args):
210|     x = ARG(0, 0.0, float, args)
211|     y = ARG(1, 0.0, float, args)
212|     z = ARG(2, 0.0, float, args)
213| 
214|     return (x,y,z)
215| 
216| v0 = vector_object()
217| v1 = vector_object(21)
218| v2 = vector_object(21, 42)
219| v3 = vector_object(21, 42, 63)
220| print(f'{v0 = }')
221| print(f'{v1 = }')
222| print(f'{v2 = }')
223| print(f'{v3 = }')
224| print()
225| 
226| #:code::
227| from sys import argv
228| from examples import ARG
229| 
230| Frequency = float()
231| Amplitude = float()
232| Wavephase = float()
233| 
234| ...
235| 
236| def main ():
237|     '''Module entry function.'''
238|     print(f'{Frequency = }')
239|     print(f'{Amplitude = }')
240|     print(f'{Wavephase = }')
241|     ...
242| 
243| if __name__ == '__main__':
244|     # First argument is name of this script...
245|     print(argv[0])
246|     print()
247| 
248|     # Handle provided command line arguments...
249|     Frequency = ARG(1, 5.0, float, argv)
250|     Amplitude = ARG(2, 1.0, float, argv)
251|     Wavephase = ARG(3, 0.0, float, argv)
252| 
253|     # Call main function...
254|     main()
255| 
256| #:end:code::
257|