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)

list(foo(5))

Viewing the source for classes/modules

Works great with syntax highlighting.

import inspect

inspect.getsource(azureml.automl.runtime.featurization.data_transformer)

Checking if an object has a certain property/method

if hasattr(myobject, 'myprop'):
    dostuff()

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

– 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:

[FreeTDS]
Description=FreeTDS Driver for Linux & MSSQL
Driver=/usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsodbc.so
UsageCount=1
# 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/libtdsodbc.so;Server={server};Database={database};Uid={user};Pwd={pass};Port={most_likely_1433}'

pyodbc.connect(connection_str)

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

try:
    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