• Add a Python’s debugger break point:

    import pdb; pdb.set_trace()
    
  • Replace accentuated characters by their ASCII equivalent in a unicode string:

    import unicodedata
    unicodedata.normalize('NFKD', u"éèàçÇÉȲ³¼ÀÁÂÃÄÅËÍÑÒÖÜÝåïš™").encode('ascii', 'ignore')
    
  • Lambda function to transform a string to a URL-friendly ID:

    getSafeURL = lambda s: '-'.join([w for w in ''.join([c.isalnum() and c or '-' for c in s.lower()]).split('-') if w])
    

Better: use awesome-slugify package.

  • Sort a list of dicts by dict-key (source):

    import operator
    [dict(a=1, b=2, c=3), dict(a=2, b=2, c=2), dict(a=3, b=2, c=1)].sort(key=operator.itemgetter('c'))
    
  • Set urllib2 timeout (source):

    import socket
    socket.setdefaulttimeout(10)
    
  • Start a dumb HTTP server on port 8000 (source):

    $ python -m SimpleHTTPServer 8000
    
  • Use autopep8 to apply PEP8’s coding style on all Python files:

    $ find ./ -iname "*.py" -exec autopep8 --in-place "{}" \;
    
  • Delete all .pyc and .pyo files in the system:

    $ find / -name "*.py[co]" -delete
    

Date and Time

I personnaly recommend using the Arrow package. But if you can’t, here are pure-python snippets:

  • Add a month to the current date:
    import datetime
    import dateutil
    datetime.date.today() + dateutil.relativedelta(months=1)
    

Jinja

To generate curly braces:

>>> from jinja2 import Template
>>> Template(u""" Yo! """).render()
u' Yo! '
>>> Template(u""" {{'{{'}} """).render()
u' {{ '
>>> Template(u""" {{'{'}} """).render()
u' { '
>>> Template(u""" {{'{'}}machin{{'}'}} """).render()
u' {machin} '

Data

Package Management

  • Generate a binary distribution of the current package:

    $ python ./setup.py sdist
    
  • Register, generate and upload to PyPi the current package as a source package, an egg and a dumb binary:

    $ python ./setup.py register sdist bdist_egg bdist_dumb upload
    

Configuration

I maintain a set of default configuration files in my dotfiles repository:

Related content