2025-07-21_simple-python-tricks-16.html
001|
002|
003|
004|
005| class test_bag (dict):
006|
007| def __new__ (cls, **kwargs):
008| """Create a new test_bag instance."""
009| print(f'new({kwargs.keys()})')
010|
011| obj = super().__new__(cls, **kwargs)
012| print(f'self={obj}')
013| return obj
014|
015| def __init__ (self, **kwargs):
016| """Initialize a new test_bag instance."""
017| print(f'init({kwargs.keys()})')
018| super().__init__()
019|
020|
021| for kx,k in enumerate(kwargs):
022| a = kwargs[k]
023| print(f'arg[{kx}] {k}="{a}"')
024| self[k] = a
025|
026| def __missing__ (self, keyname):
027| """No entry in collection for keyname."""
028| print(f'missing({keyname})')
029|
030| return None
031|
032| def __getitem__ (self, keyname):
033| """Get Item. val = obj[key]"""
034| print(f'getitem({keyname})')
035|
036| return super().__getitem__(keyname)
037|
038| def __setitem__ (self, keyname, value):
039| """Set Item. {obj[key]=val}"""
040| print(f'setitem({keyname},{value})')
041|
042| if keyname in self:
043| raise ValueError('Values are read-only.')
044| super().__setitem__(keyname, value)
045|
046| def visit (self, callback_function):
047| """Visit each item in the bag."""
048|
049|
050| for ix,key in enumerate(self.keys(), start=1):
051| print(f'visit[{ix}]: "{key}" = "{self[key]}"')
052|
053| retval = callback_function(ix, key, self[key])
054|
055| if retval is not None:
056|
057| super().__setitem__(key, retval)
058|
059| return self
060|
061|
062| if __name__ == '__main__':
063| """Exercise the test_bag."""
064|
065| def print_function (ix, key, value):
066| print(f'{ix}: {key}="{value}" ({type(value).__name__})')
067|
068| bag = test_bag(x=1.0, y=0.0, z=0.0, a=True, b=False)
069| print()
070|
071| print('Visit...')
072| bag.visit(print_function)
073| print()
074|
075|
076| from time import time
077| from datetime import datetime, timedelta, tzinfo
078| from random import random
079|
080| UID = lambda: (int(1000*time()) * int((2**22)*random()))
081|
082| class TimeZone (tzinfo):
083| """A TimeZone class (extending tzinfo)."""
084|
085|
086| DST0 = datetime(2018, 3, 11, 2, 0, 0)
087| DST1 = datetime(2018, 11, 4, 2, 0, 0)
088|
089|
090| HOUR = timedelta(hours=1)
091| ZERO = timedelta(0)
092|
093| def utcoffset (self, dt):
094| """This time zone's UTC offset."""
095| return self.offset + self.dst(dt)
096|
097| def dst (self, dt):
098| """Return difference for thie time zone's DST."""
099| return self.HOUR if self._dst(dt) else self.ZERO
100|
101| def _dst (self, dt):
102| """Figure out if we're in DST now."""
103| dst0 = self.DST0.replace(year=dt.year)
104| dst1 = self.DST1.replace(year=dt.year)
105| dtx = dt.replace(tzinfo=None)
106| return dst0 <= dtx < dst1
107|
108| class UTC (TimeZone):
109| """aka GMT aka 'Zulu Time'"""
110| def tzname (self, dt):
111| return 'UTC'
112|
113| def utcoffset (self, dt):
114| return self.ZERO
115|
116| def dst (self, dt):
117| return self.ZERO
118|
119| class EST (TimeZone):
120| """Eastern Standard Time."""
121| offset = timedelta(hours=-5)
122|
123| def tzname (self, dt):
124| return 'EDT' if self._dst(dt) else 'EST'
125|
126| class CST (TimeZone):
127| """Central Standard Time."""
128| offset = timedelta(hours=-6)
129|
130| def tzname (self, dt):
131| return 'CDT' if self._dst(dt) else 'CST'
132|
133| class MST (TimeZone):
134| """Mountain Standard Time."""
135| offset = timedelta(hours=-7)
136|
137| def tzname (self, dt):
138| return 'MDT' if self._dst(dt) else 'MST'
139|
140| class PST (TimeZone):
141| """Pacific Standard Time."""
142| offset = timedelta(hours=-8)
143|
144| def tzname (self, dt):
145| return 'PDT' if self._dst(dt) else 'PST'
146|
147| class HST (TimeZone):
148| """Hawaii Standard Time."""
149| offset = timedelta(hours=-10)
150|
151| def tzname (self, dt):
152| return 'HDT' if self._dst(dt) else 'HST'
153|
154|
155| from datetime import datetime
156| from examples import UID, UTC
157|
158| class ticket (dict):
159| """Implementing a Ticket by subclassing dict."""
160|
161| def __init__ (self, firstname, lastname, **kwargs):
162| """New tickets require a first and last name."""
163| super().__init__(**kwargs)
164| self['tid'] = UID()
165| self['ts'] = datetime.now(tz=UTC())
166| self['firstname'] = firstname
167| self['lastname'] = lastname
168|
169| @property
170| def tid (self): return self['tid']
171|
172| @property
173| def name (self): return f'{self["firstname"]} {self["lastname"]}'
174|
175| @property
176| def timestamp (self): return self['ts'].strftime('%Y-%m-%d %H:%M:%S')
177|
178| def __missing__ (self, key): return '<null>'
179|
180| def __eq__ (self, other): return (self['ts'] == other['ts'])
181| def __ne__ (self, other): return (self['ts'] != other['ts'])
182| def __le__ (self, other): return (self['ts'] <= other['ts'])
183| def __lt__ (self, other): return (self['ts'] < other['ts'])
184| def __gt__ (self, other): return (self['ts'] > other['ts'])
185| def __ge__ (self, other): return (self['ts'] >= other['ts'])
186|
187| def __hash__ (self): return hash(self['tid'])
188|
189| def __setitem__ (self, keyname, value):
190| """Set Item."""
191| if keyname in self:
192| raise ValueError('Entries are read-only.')
193| super().__setitem__(keyname, value)
194|
195|
196| def __delitem__ (self, keyname):
197| """Delete Item."""
198| raise ValueError('Entries may not be deleted.')
199|
200| def __str__ (self):
201| return f'[{self.timestamp}] {self.name} ({self.tid})'
202|
203| def __repr__ (self):
204| t = (self.tid, self.timestamp, self['firstname'], self['lastname'])
205| s = '{ticket:{tid:%s, ts:"%s", firstname:"%s", lastname:"%s"}}'
206| return s%t
207|
208|
209| if __name__ == '__main__':
210| """Exercise the ticket class."""
211| print()
212|
213| tick = ticket('Wyrd','Smythe', job='123456-78', due='2025-08-14', status='new', pn=884523)
214| print(f'{tick!s}')
215| print()
216|
217|
218| from demos import ticket
219|
220| if __name__ == '__main__':
221| """Exercise the ticket class."""
222|
223|
224| tick = ticket('Wyrd','Smythe', job='123456-78', status='new')
225| print(tick)
226| print()
227|
228|
229| print(f'status1 = "{tick["status"]}"')
230| try:
231| tick['status'] = 'accepted'
232| except Exception as e:
233| print(e)
234| print()
235|
236|
237| try:
238| del tick['status']
239| except Exception as e:
240| print(e)
241| print()
242|
243|
244| try:
245| tick['status2'] = 'open'
246| print(f'status2 = "{tick["status2"]}"')
247| print()
248| except Exception as e:
249| print(e)
250| print()
251|
252|
253| try:
254| tick['status2'] = 'closed'
255| except Exception as e:
256| print(e)
257| print()
258|
259|
260| super(type(tick), tick).__setitem__('status', 'accepted')
261| super(type(tick), tick).__setitem__('status2', 'closed')
262| print(f'status1 = "{tick["status"]}"')
263| print(f'status2 = "{tick["status2"]}"')
264| print()
265|
266|
267| from time import sleep
268| from demos import ticket
269|
270| if __name__ == '__main__':
271| """Exercise the ticket class."""
272|
273| t1 = ticket('Wyrd','Smythe', job='123456-78')
274| print(t1)
275| sleep(3)
276|
277| t2 = ticket('Fred', 'Flintstone', job='123789-34')
278| print(t2)
279| sleep(3)
280|
281| t3 = ticket('Barney', 'Rubble', job='567258-42')
282| print(t3)
283| print()
284|
285| print(f'{t1 < t2 = }')
286| print(f'{t2 < t3 = }')
287| print()
288|
289| for ix,tick in enumerate(sorted([t3,t1,t2]), start=1):
290| print(f'{ix}: {tick.name}')
291| print()
292|
293|
294| from time import sleep
295| from random import shuffle
296| from demos import ticket
297|
298| if __name__ == '__main__':
299| """Exercise the ticket class."""
300| ticks = []
301|
302| def new_ticket (fn, ln):
303| ticks.append(ticket(fn, ln))
304| print(ticks[-1])
305| sleep(3)
306|
307| new_ticket('Joe','Ryan')
308| new_ticket('Byron', 'Buxton')
309| new_ticket('Trevor', 'Larnach')
310| new_ticket('Willie','Castro')
311| new_ticket('Carlos','Correa')
312| new_ticket('Kody','Clemens')
313| new_ticket('Ty','France')
314| new_ticket('Matt','Wallner')
315| new_ticket('Harrison','Bader')
316| new_ticket('Royce','Lewis')
317| new_ticket('Christian','Vazquez')
318| print()
319|
320| shuffle(ticks)
321| for ix,tick in enumerate(ticks, start=1):
322| print(f'{ix:2d}: {tick.name}')
323| print()
324|
325|
326| for ix,tick in enumerate(sorted(ticks), start=1):
327| print(f'{ix:2d}: {tick.name}')
328| print()
329|
330|
331| from os import path, listdir
332|
333| class filelist (dict):
334| """Load a dictionary with a list of files from a directory."""
335|
336| def __init__ (self, filepath):
337| """New filelist. Loads data dynamically."""
338| super().__init__()
339| self.fpath = filepath
340|
341|
342| for name in listdir(filepath):
343| fn = path.join(self.fpath, name)
344|
345|
346| if path.isfile(fn):
347| self[name] = {
348| '@':1,
349| 'name':fn,
350| 'size':path.getsize(fn),
351| 'dlm':path.getmtime(fn),
352| 'dcr':path.getmtime(fn),
353| }
354| continue
355|
356|
357| if path.isdir(fn):
358| self[name] = {
359| '@':2,
360| 'name':fn
361| }
362| continue
363|
364|
365| raise RuntimeError(f'Unknown directory type: {name}')
366|
367| def __repr__ (self):
368| return f'{self.fpath} ({len(self)})'
369|
370|
371| if __name__ == '__main__':
372| """Exercise the filelist class."""
373|
374|
375| flist = filelist(r'C:\demo\hcc\python')
376| print(flist)
377|
378|
379| sort_by_type = lambda k:flist[k]['@']
380|
381|
382| for name in sorted(flist, key=sort_by_type, reverse=True):
383| rcd = flist[name]
384| match rcd['@']:
385|
386|
387| case 1:
388| size = f'{rcd["size"]:,}'
389| print(f'{name:<24s}{size:>8s} bytes')
390|
391|
392| case 2:
393| print(f'{name:24s}(subdirectory)')
394|
395| print()
396|
397|
398| class inifile (dict):
399|
400| def __init__ (self, filename, encoding='utf8'):
401| """New inifile. Loads data dynamically."""
402| super().__init__()
403| self.fname = filename
404|
405|
406| fp = open(filename, mode='r', encoding=encoding)
407| try:
408| print(f'reading: {filename}...')
409| sect_name = 'main'
410| self[sect_name] = {}
411|
412| for ix,line in enumerate(fp, start=1):
413| line = line.strip()
414|
415|
416|
417| if len(line) == 0:
418| continue
419|
420|
421| if line.startswith('#') or line.startswith(';'):
422| continue
423|
424|
425| if line.startswith('['):
426|
427| if line[-1] != ']':
428| SyntaxError(f'Invalid section header: "{line}"')
429| sect_name = line[1:-1].strip()
430| self[sect_name] = {}
431| continue
432|
433|
434| parts = line.split('=', maxsplit=1)
435| name = parts[0].strip()
436| valu = parts[1].strip() if 1 < len(parts) else ''
437| self[sect_name][name] = valu
438|
439| print()
440| except:
441| raise
442| finally:
443| fp.close()
444|
445| def __repr__ (self):
446| return f'{self.fname} ({len(self)} sections)'
447|
448|
449| if __name__ == '__main__':
450| """Exercise the inifile class."""
451|
452|
453| ini = inifile(r"C:\demo\hcc\python\configuration.ini")
454| print(f'INI File: {ini.fname}')
455|
456|
457| for sect in ini:
458| print(f'Section: "{sect}"')
459| for ix,name in enumerate(ini[sect], start=1):
460| print(f'{ix:2d}: {name}={ini[sect][name]}')
461| print()
462| print()
463|
464|
465|