{{ leftover_code }}

Stuff I can't seem to remember in Python

Even though I've been programming Python for years, there are a handful of things I can't remember for the life of me. I'm putting them down here for my own ease of lookup, but maybe they will help someone else in the future.

Slugify a String

The Django framework has a slugify function in django.utils.text that makes a string URL-friendly. I find this very useful when I'm creating filenames as well.

import unicodedata
import re

def slugify(value):
    """ Note: This was modified from django.utils.text slugify """
    value = unicode(value.decode('UTF-8'))
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = value.decode('ascii')
    value = re.sub('[^\w\s-]', '', value).strip().lower()
    value = re.sub('[-\s]+', '-', value)
    return str(value)

> print slugify("Thé h@ppy dog went ~ and came back!")
> the-hppy-dog-went-and-came-back

Get the Current Directory

I don't know why I can't remember this.

import os

CUR_DIR = os.path.dirname(os.path.realpath(__file__))

Set up Jinja2 Template Rendering

A number of configuration options need to be set and I have to look them up all the time.

import jinja2

# Set up the template engine to look in the current directory
template_loader = jinja2.FileSystemLoader('./')
template_env = jinja2.Environment(loader=template_loader)

# Load the template file
template_file = "mytemplate.html"
template = template_env.get_template(template_file)

# Render the template
context = {'foo': 'bar'}
output = template.render(context)

Combine Two Equal-Sized Lists into a Dictionary

I use this all the time when working with CSV files.

list1 = ["Column A", "Column B", "Column C"]
list2 = ["Value 1", "Value 2", "Value 3"]

dict(zip(list1, list2))
{'Column B': 'Value 2', 'Column C': 'Value 3', 'Column A': 'Value 1'}

Fixing pip install clang error

As of XCode 5.1, the LLVM compiler throws errors for unrecognized command-line options. When trying to do something like pip install lxml, I would see these errors:

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
error: command 'cc' failed with exit status 1

To fix this error, you can use the ARCHFLAGS environment variable to downgrade the error into a warning:


If you use virtualenvwrapper, (and you should!) you can add the line to your /bin/postactivate shell script so you won't have to remember to do it in the future when adding packages:

#This hook is run after this virtualenv is activated.

Note: This is going to break in the future, but it will get you by for now.

I'll keep adding items as they come up.