2025-08-25_simple-python-tricks-18.html
001|
002|
003|
004|
005| typename = lambda obj: type(obj).__name__
006|
007|
008| from examples import typename
009|
010| if __name__ == '__main__':
011| a = 42
012| b = '42'
013| c = (21, 42, 63, 84)
014| d = [86, 99]
015| e = object()
016|
017| print(f'a: {typename(a)}')
018| print(f'b: {typename(b)}')
019| print(f'c: {typename(c)}')
020| print(f'd: {typename(d)}')
021| print(f'e: {typename(e)}')
022| print()
023|
024|
025| from examples import typename
026|
027| class Word:
028| '''Implements a Word as a list of characters (a string).'''
029|
030| def __init__ (self, text):
031| '''Initialize new Word instance.'''
032| self.chars = text
033|
034| def __bool__ (self):
035| '''A Word is True if it has non-zero length.'''
036| return (0 < len(self.chars))
037|
038| def __len__ (self):
039| '''Return Word length.'''
040| return len(self.chars)
041|
042| def __getitem__ (self, idx):
043| '''Return a character by index.'''
044| return self.chars[idx]
045|
046| def __iter__ (self):
047| '''Return an interater over the Word characters.'''
048| return iter(self.chars)
049|
050| def __repr__ (self):
051| '''Return a REPR string.'''
052| return f'<{typename(self)} @{id(self):08x}>'
053|
054| def __str__ (self):
055| '''Word string is just its characters.'''
056| return self.chars
057|
058|
059| if __name__ == '__main__':
060|
061|
062| wrd = Word("Hello")
063|
064| print(f'String: {wrd!s}')
065| print(f'REPR: {wrd!r}')
066| print(f'bool: {bool(wrd)}')
067| print(f'len: {len(wrd)}')
068| print(f'[2]: {wrd[2]}')
069| print()
070| for ix,char in enumerate(wrd):
071| print(f'{ix}: {char}')
072| print()
073|
074|
075| from examples import typename, Word
076|
077| class Sentence:
078| '''Implements a Sentence as a list of Words.'''
079|
080| def __init__ (self, text):
081| '''Initialize new Sentence instance.'''
082| self.words = [Word(word) for word in text.split()]
083|
084| def __bool__ (self):
085| '''A Sentence is True if it has non-zero length.'''
086| return (0 < len(self.words))
087|
088| def __len__ (self):
089| '''Return Sentence length.'''
090| return len(self.words)
091|
092| def __getitem__ (self, idx):
093| '''Return a character by index.'''
094| return self.words[idx]
095|
096| def __iter__ (self):
097| '''Return an interater over the Sentence words.'''
098| return iter(self.words)
099|
100| def __repr__ (self):
101| '''Return a REPR string.'''
102| return f'<{typename(self)} @{id(self):08x}>'
103|
104| def __str__ (self):
105| '''Sentence string is its words joined by spaces.'''
106| return ' '.join(str(w) for w in self.words)
107|
108|
109| if __name__ == '__main__':
110|
111|
112| snt = Sentence("Now is the time for all good people to party.")
113|
114| print(f'String: {snt!s}')
115| print(f'REPR: {snt!r}')
116| print(f'bool: {bool(snt)}')
117| print(f'len: {len(snt)}')
118| print(f'[2]: {snt[2]}')
119| print()
120| for ix,wrd in enumerate(snt):
121| print(f'{ix}: {wrd}')
122| print()
123|
124|
125| from examples import typename, Sentence
126|
127| class Paragraph:
128| '''Implements a Paragraph as a list of Sentences.'''
129|
130| def __init__ (self, text):
131| '''Initialize new Paragraph instance.'''
132| self.lines = [Sentence(s) for s in text.split('.') if 0 < len(s)]
133|
134| def __bool__ (self):
135| '''A Paragraph is True if it has non-zero length.'''
136| return (0 < len(self.lines))
137|
138| def __len__ (self):
139| '''Return Paragraph length.'''
140| return len(self.lines)
141|
142| def __getitem__ (self, idx):
143| '''Return a character by index.'''
144| return f'{self.lines[idx]}.'
145|
146| def __iter__ (self):
147| '''Return an interater over the Paragraph sentences.'''
148| return iter(self.lines)
149|
150| def __repr__ (self):
151| '''Return a REPR string.'''
152| return f'<{typename(self)} @{id(self):08x}>'
153|
154| def __str__ (self):
155| '''Paragraph string is its sentences joined by spaces.'''
156| return ' '.join(f'{s}.' for s in self.lines)
157|
158|
159| if __name__ == '__main__':
160|
161|
162| par = Paragraph("Hello, World! How are you. I am fine. Good-bye now.")
163|
164| print(f'String: {par!s}')
165| print(f'REPR: {par!r}')
166| print(f'bool: {bool(par)}')
167| print(f'len: {len(par)}')
168| print(f'[2]: {par[2]}')
169| print()
170| for ix,snt in enumerate(par):
171| print(f'{ix}: {par[ix]}')
172| print(f'{ix}: {snt}')
173| print()
174|
175|
176| from examples import typename, Paragraph
177|
178| class Section:
179| '''Implements a Section as a list of Paragraphs.'''
180|
181| def __init__ (self, text):
182| '''Initialize new Section instance.'''
183| self.paras = [Paragraph(p) for p in text.split('\n\n')]
184|
185| def __bool__ (self):
186| '''A Section is True if it has non-zero length.'''
187| return (0 < len(self.paras))
188|
189| def __len__ (self):
190| '''Return Section length.'''
191| return len(self.paras)
192|
193| def __getitem__ (self, idx):
194| '''Return a character by index.'''
195| return self.paras[idx]
196|
197| def __iter__ (self):
198| '''Return an interater over the Section paragraphs.'''
199| return iter(self.paras)
200|
201| def __repr__ (self):
202| '''Return a REPR string.'''
203| return f'<{typename(self)} @{id(self):08x}>'
204|
205| def __str__ (self):
206| '''Section string is its paragraphs joined by blank lines.'''
207| return '\n\n'.join(str(s) for s in self.paras)
208|
209|
210| if __name__ == '__main__':
211| text = """\
211| Hello. Just a brief paragraph. Good-bye.
211|
211| Hello, again. I'm back.
211|
211| But now I'm leaving. See you later."""
212|
213| sec = Section(text)
214|
215| print(f'String: {sec!s}')
216| print(f'REPR: {sec!r}')
217| print(f'bool: {bool(sec)}')
218| print(f'len: {len(sec)}')
219| print(f'[2]: {sec[2]}')
220| print()
221| for ix,par in enumerate(sec):
222| print(f'{ix}: {par}')
223| print()
224|
225|
226| from examples import Section
227|
228| DemoText = """\
228| Some of our group was already in Boston when the six of us arrived.
228| Others arrived slightly later or the next day. Those who were there
228| met in the Lobby to go hunt dinner. The convention is held annually,
228| so many of our group knew Boston and had ideas about interesting
228| places to go. This, to me, is better than eating at the hotel or
228| trying to find someplace nearby. When I travel, I hate eating or
228| doing anything I could do at home, so I was delighted to explore.
228|
228| Lunch each of the four days was served in a large room. I have to
228| give Marriott low marks for its conference lunch service. That first
228| day, they served a shrimp/scallops-in-cream-sauce thing that, while
228| I liked it, is problematic. Some people don't care for seafood or
228| suffer allergic reactions to it. Not a great idea for a mass lunch,
228| I think. (Although it is Boston.) One member of our group doesn't eat
228| things that "live in shells" (interesting rule), and had to wait
228| nearly to the end of lunch to get her alternate.
228| """
229|
230| def main ():
231| print(DemoText)
232| print()
233|
234| txtobj = Section(DemoText)
235| print(txtobj)
236| print()
237|
238| for px,para in enumerate(txtobj):
239| print(f'Paragraph {px}')
240|
241| for sx,sent in enumerate(para):
242| print(f'Sentence {sx}')
243|
244| for wx,word in enumerate(sent):
245| print(f'{wx:2d}: {word}')
246|
247| print()
248| print()
249| print()
250|
251|
252| return txtobj
253|
254|
255| if __name__ == '__main__':
256| print()
257| txt = main()
258| print()
259|
260|
261| class TextObject:
262| '''Basic Text Object. Implements repr.'''
263|
264| def __repr__ (self):
265| return f'<{type(self).__name__} @{id(self):08x}>'
266|
267|
268| class Word2 (TextObject):
269|
270| def __init__ (self, text):
271| '''Initialize new Word instance.'''
272| self.chars = list(text)
273|
274| def __bool__ (self):
275| '''A Word is True if it has non-zero length.'''
276| return (0 < len(self.chars))
277|
278| def __len__ (self):
279| '''Return Word length.'''
280| return len(self.chars)
281|
282| def __getitem__ (self, idx):
283| '''Return a character by index.'''
284| return self.chars[idx]
285|
286| def __iter__ (self):
287| '''Return an interater over the Word characters.'''
288| return iter(self.chars)
289|
290| def __str__ (self):
291| '''Word string is just its characters.'''
292| return self.chars
293|
294|
295| class TextObject:
296|
297| def __init__ (self):
298| '''Initialize new TextObject instance.'''
299| self.content = None
300|
301| def __bool__ (self):
302| '''True if non-zero length.'''
303| return (0 < len(self.content))
304|
305| def __len__ (self):
306| '''Return length.'''
307| return len(self.content)
308|
309| def __getitem__ (self, idx):
310| '''Return a content item by index.'''
311| return self.content[idx]
312|
313| def __iter__ (self):
314| '''Return an interater over the content.'''
315| return iter(self.content)
316|
317| def __repr__ (self):
318| '''Generic REPR string.'''
319| return f'<{type(self).__name__} @{id(self):08x}>'
320|
321|
322| class Word2 (TextObject):
323| '''Implements a Word as a list of characters (a string).'''
324|
325| def __init__ (self, text):
326| '''Initialize new Word instance.'''
327| self.content = list(text)
328|
329| def __str__ (self):
330| '''Word string is just its characters.'''
331| return ''.join(self.content)
332|
333|
334| class Sentence2 (TextObject):
335| '''Implements a Sentence as a list of Words.'''
336|
337| def __init__ (self, text):
338| '''Initialize new Word instance.'''
339| self.content = [Word2(w) for w in text.split()]
340|
341| def __str__ (self):
342| '''Sentence string is its words joined by spaces.'''
343| return ' '.join(str(w) for w in self.content)
344|
345|
346| class Paragraph2 (TextObject):
347| '''Implements a Paragraph as a list of Sentences.'''
348|
349| def __init__ (self, text):
350| '''Initialize new Word instance.'''
351| self.content = [Sentence2(s) for s in text.split('.') if 0 < len(s)]
352|
353| def __getitem__ (self, idx):
354| '''Return a character by index.'''
355| return f'{self.lines[idx]}.'
356|
357| def __str__ (self):
358| '''Paragraph string is its sentences joined by spaces.'''
359| return ' '.join(f'{s}.' for s in self.content)
360|
361|
362| class Section2 (TextObject):
363| '''Implements a Section as a list of Paragraphs.'''
364|
365| def __init__ (self, text):
366| '''Initialize new Word instance.'''
367| self.content = [Paragraph2(p) for p in text.split('\n\n')]
368|
369| def __str__ (self):
370| '''Section string is its paragraphs joined by newlines.'''
371| return '\n\n'.join(str(p) for p in self.content)
372|
373|
374| DemoText = """\
374| Some of our group was already in Boston when the six of us arrived.
374| Others arrived slightly later or the next day. Those who were there
374| met in the Lobby to go hunt dinner. The convention is held annually,
374| so many of our group knew Boston and had ideas about interesting
374| places to go. This, to me, is better than eating at the hotel or
374| trying to find someplace nearby. When I travel, I hate eating or
374| doing anything I could do at home, so I was delighted to explore.
374|
374| Lunch each of the four days was served in a large room. I have to
374| give Marriott low marks for its conference lunch service. That first
374| day, they served a shrimp/scallops-in-cream-sauce thing that, while
374| I liked it, is problematic. Some people don't care for seafood or
374| suffer allergic reactions to it. Not a great idea for a mass lunch,
374| I think. (Although it is Boston.) One member of our group doesn't eat
374| things that "live in shells" (interesting rule), and had to wait
374| nearly to the end of lunch to get her alternate."""
375|
376| if __name__ == '__main__':
377| print()
378|
379| txtobj = Section2(DemoText)
380| print(txtobj)
381| print()
382|
383|
384| from examples import TextObject, Sentence2
385|
386| class Paragraph3 (TextObject):
387| '''Implements a Paragraph as a list of Sentences.'''
388|
389| def __init__ (self, text):
390| '''Initialize new Paragraph instance. (Improved version.)'''
391| self.content = []
392|
393| buf = []
394| for char in text:
395| if char in ['.', '!', '?']:
396| buf.append(char)
397| self.content.append(Sentence2(''.join(buf).strip()))
398| buf = []
399| else:
400| buf.append(char)
401|
402| if 0 < len(buf):
403| self.content.append(Sentence2(''.join(buf).strip()))
404|
405| def __str__ (self):
406| '''Paragraph string is its sentences joined by spaces.'''
407| text = ' '.join(str(s) for s in self.content)
408|
409| text = text.replace('( ', '(')
410| text = text.replace(' )', ')')
411| return text
412|
413|
414| if __name__ == '__main__':
415|
416|
417| par = Paragraph3("Hello, World! How are you. I am fine. Good-bye now.")
418|
419| print(f'String: {par!s}')
420| print(f'REPR: {par!r}')
421| print(f'bool: {bool(par)}')
422| print(f'len: {len(par)}')
423| print(f'[2]: {par[2]}')
424| print()
425| for ix,snt in enumerate(par):
426| print(f'{ix}: {par[ix]}')
427| print(f'{ix}: {snt}')
428| print()
429|
430|
431| from examples import Section3
432|
433| DemoText = """\
433| Some of our group was already in Boston when the six of us arrived.
433| Others arrived slightly later or the next day. Those who were there
433| met in the Lobby to go hunt dinner. The convention is held annually,
433| so many of our group knew Boston and had ideas about interesting
433| places to go. This, to me, is better than eating at the hotel or
433| trying to find someplace nearby. When I travel, I hate eating or
433| doing anything I could do at home, so I was delighted to explore.
433|
433| Lunch each of the four days was served in a large room. I have to
433| give Marriott low marks for its conference lunch service. That first
433| day, they served a shrimp/scallops-in-cream-sauce thing that, while
433| I liked it, is problematic. Some people don't care for seafood or
433| suffer allergic reactions to it. Not a great idea for a mass lunch,
433| I think. (Although it is Boston.) One member of our group doesn't eat
433| things that "live in shells" (interesting rule), and had to wait
433| nearly to the end of lunch to get her alternate."""
434|
435| if __name__ == '__main__':
436|
437| txtobj = Section3(DemoText)
438| print(txtobj)
439| print()
440|
441| sent = txtobj[0][2]
442| word = txtobj[0][2][4]
443| char = txtobj[0][2][4][-1]
444|
445| print(f'{sent=!s}')
446| print(f'{word=!s}')
447| print(f'{char=!s}')
448| print()
449|
450|
451| para0,para1,*_ = txtobj
452| sent0,sent1,*_ = para1
453| word0,word1,*_ = sent1
454| char0,char1,*_ = word1
455| print(f'{sent1=!s}')
456| print(f'{word1=!s}')
457| print(f'{char1=!s}')
458| print()
459|
460|
461| class TextObject4 (list):
462|
463| def __repr__ (self):
464| '''Generic REPR string.'''
465| return f'<{type(self).__name__} @{id(self):08x}>'
466|
467| class Word4 (TextObject4):
468| '''Implements a Word as a list of characters (a string).'''
469|
470| def __init__ (self, text):
471| '''Initialize new Word instance.'''
472| super().__init__(text)
473|
474| def __str__ (self):
475| '''Word string is just its characters.'''
476| return ''.join(self)
477|
478| class Sentence4 (TextObject4):
479| '''Implements a Sentence as a list of Words.'''
480|
481| def __init__ (self, text):
482| '''Initialize new Word instance.'''
483| super().__init__(Word4(w) for w in text.split())
484|
485| def __str__ (self):
486| '''Sentence string is its words joined by spaces.'''
487| return ' '.join(str(w) for w in self)
488|
489| class Paragraph4 (TextObject4):
490| '''Implements a Paragraph as a list of Sentences.'''
491|
492| def __init__ (self, text):
493| '''Initialize new Paragraph instance.'''
494| buf = []
495| tmp = []
496| for char in text:
497| if char in ['.', '!', '?']:
498| tmp.append(char)
499| buf.append(Sentence4(''.join(tmp).strip()))
500| tmp = []
501| else:
502| tmp.append(char)
503|
504| if 0 < len(tmp):
505| buf.append(Sentence4(''.join(tmp).strip()))
506| super().__init__(buf)
507|
508| def __str__ (self):
509| '''Paragraph string is its sentences joined by spaces.'''
510| text = ' '.join(str(s) for s in self)
511|
512| text = text.replace('( ', '(')
513| text = text.replace(' )', ')')
514| return text
515|
516| class Section4 (TextObject4):
517| '''Implements a Section as a list of Paragraphs.'''
518|
519| def __init__ (self, text):
520| '''Initialize new Word instance.'''
521| super().__init__(Paragraph4(p) for p in text.split('\n\n'))
522|
523| def __str__ (self):
524| '''Section string is its paragraphs joined by newlines.'''
525| return '\n\n'.join(str(p) for p in self)
526|
527|
528| from examples import Section4
529|
530| DemoText = """\
530| Some of our group was already in Boston when the six of us arrived.
530| Others arrived slightly later or the next day. Those who were there
530| met in the Lobby to go hunt dinner. The convention is held annually,
530| so many of our group knew Boston and had ideas about interesting
530| places to go. This, to me, is better than eating at the hotel or
530| trying to find someplace nearby. When I travel, I hate eating or
530| doing anything I could do at home, so I was delighted to explore.
530|
530| Lunch each of the four days was served in a large room. I have to
530| give Marriott low marks for its conference lunch service. That first
530| day, they served a shrimp/scallops-in-cream-sauce thing that, while
530| I liked it, is problematic. Some people don't care for seafood or
530| suffer allergic reactions to it. Not a great idea for a mass lunch,
530| I think. (Although it is Boston.) One member of our group doesn't eat
530| things that "live in shells" (interesting rule), and had to wait
530| nearly to the end of lunch to get her alternate."""
531|
532| if __name__ == '__main__':
533|
534| txtobj = Section4(DemoText)
535| print(txtobj)
536| print()
537|
538|
539|