Table of Contents

Using nested generators

Starting with Python 3.3, you can use delegated generators

def foo(x):
    yield from range(x, 0, -1)
    yield from range(x)


Viewing the source for classes/modules

Works great with syntax highlighting.

import inspect


Checking if an object has a certain property/method

if hasattr(myobject, 'myprop'):

if hasattr(myobject, 'myfunction') and callable(myobject.myfunction):

– via StackOverflow

Connecting to MS SQL Server with SQLAlchemy

Using pymssql

pip install pymssql
pip install sqlalchemy

# Macs need FreeTDS, too
brew install unixodbc freetds
connection_str = 'mssql+pymssql://{user}:{pass}@{host}/{db}'

– via PyODBC docs and SQLAlchemy docs. Microsoft Docs is a good resource, too

Using (shudder) pyodbc

pip install pymssql
pip install sqlalchemy

# Macs need FreeTDS, too
brew install unixodbc freetds

But wait, there’s more! Run odbcinst -j to get the location of the odbcinst.ini (probably in the directory /usr/local/etc/). Edit odbcinst.ini to include the following:

Description=FreeTDS Driver for Linux & MSSQL
# Option A - needs the bit above added in odbcinst.ini
connection_str = 'Driver={FreeTDS};Server={server};Database={database};Uid={user};Pwd={pass};Port={most_likely_1433}'

# Option B - doesn't need **any** to edit any files, but you end up inserting paths in connection strings
connection_str = 'Driver=/usr/local/lib/;Server={server};Database={database};Uid={user};Pwd={pass};Port={most_likely_1433}'


You can spend time doing much, much more configuration work as seen here, but this is the least amount of configuration I was able to get away with.

Adding time periods to dates

import datetime

date = datetime(2021, 3, 5) + datetime.timedelta(days=6)

– via Stack Overflow

Format exception as string, including its stack trace

It’s all done using the traceback module.

import traceback

    raise Exception
except Exception as e:
    print(str(e))                        # prints just the exception's message
    print(traceback.format_exc())   # prints the entire stack trace, too

– via Stack Overflow

How to reload a module used in a Jupyter Notebook (or elsewhere)

import data_source          # the module you're trying to reload

import importlib            # only works in Python 3.4+

– via Stack Overflow and GeeksForGeeks

Format numbers to fixed decimals with Mako

#instead of


– via Stack Overflow

Open a local html file in the browser (useful for testing Mako templates 🙂)

import os
import webbrowser'file://' + os.path.realpath('out.html'))

– via Stack Overflow

Timezone conversion using pandas and pytz

tz_localize is ❤️

import pytz
import pandas as pd

date = '2021-01-04' 
pd.to_datetime(date)                                                                        # Timestamp('2021-01-04 00:00:00')
pd.to_datetime(date, utc=True)                                                              # Timestamp('2021-01-04 00:00:00+0000', tz='UTC')
pd.to_datetime(date).tz_localize(pytz.timezone('Europe/Bucharest'))                         # Timestamp('2021-01-04 00:00:00+0200', tz='Europe/Bucharest')
pd.to_datetime(date).tz_localize(pytz.timezone('Europe/Bucharest')).astimezone(pytz.utc)    # Timestamp('2021-01-03 22:00:00+0000', tz='UTC')

– some info via Stack Overflow

*ImportError: Start directory is not importable: * when running unit tests from PyCharm

I’ve had this happen when running python -m unittest discover -s ./tests -t <path_to_your_project_dir> from PyCharm/console, while at the same time python -m unittest discover -s ./tests succeeded.

The solution was to create an empty file in the ./tests directory.

– via Stack Overflow, and PyCharm Docs

Case insensitive string comparison

Use casefold().

print('hello'.casefold() == 'world'.casefold())

print('i'.casefold() in 'team'.casefold())

Sorting a list of dictionaries by a value in the dictionary

newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])

– via Stack Overflow