Partial port to Python (from Ruby).