Less known bits of the Python Standard Library

It’s not unusual for me to search the web for how to do something in Python and end up using a third party library only to find out later that the standard library included a module that did more or less what I wanted. Here are a couple of less known modules that might come in handy.

textwrap

>>> import textwrap
>>> text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'
>>> for line in textwrap.wrap(text, 50):
... print(line)
...
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.

pprint

>>> from pprint import pprint
>>> data = {
... 'name': 'Michael Audrey Meyers',
... 'birth_date': 'October 19, 1957',
... 'relatives' : [
... 'Donald Meyers',
... 'Edith Meyers',
... 'Judith Meyers',
... ],
... }
>>> print(data)
{'name': 'Michael Audrey Meyers', 'birth_date': 'October 19, 1957', 'relatives': ['Donald Meyers', 'Edith Meyers', 'Judith Meyers']}
>>> pprint(data)
{'birth_date': 'October 19, 1957',
'name': 'Michael Audrey Meyers',
'relatives': ['Donald Meyers', 'Edith Meyers', 'Judith Meyers']}

enum

>>> from enum import Enum
>>> class Color(Enum):
... RED = 1
... GREEN = 2
... BLUE = 3
...
>>> print(Color.RED)
Color.RED
>>> print(Color.RED.name)
RED
>>> print(Color.RED.value)
1

shelve

>>> import shelve
>>> with shelve.open('default.db') as shelf:
... shelf['first_name'] = 'Vitor'
... shelf['last_name'] = 'Pereira'
...
>>> with shelve.open('default.db') as shelf:
... print(shelf['first_name'], shelf['last_name'])
...
Vitor Pereira

(Read the bit on writebackin the documentation if you plan on making heavier use of this module)

email and smtplib

import smtplib
from email.message import EmailMessage
textfile = 'stored_email.txt'# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())

msg['Subject'] = f'The contents of {textfile}'
msg['From'] = 'roger@hmail.com'
msg['To'] = 'tobias@imail.com'

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

winreg

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store