Strings

  • Replace accentuated characters by their ASCII equivalent in a unicode string:

    1import unicodedata
    2
    3unicodedata.normalize("NFKD", "éèàçÇÉȲ³¼ÀÁÂÃÄÅËÍÑÒÖÜÝåïš™").encode("ascii", "ignore")
    
  • Cleanest way I found to produce slugified / tokenized strings, based on boltons.strutils  :

    >>> from boltons import strutils
    >>> strutils.slugify(" aBc De F   1 23 4! -- ! 56--78 - -9- %$& +eée-", "-", ascii=True)
    b'abc-de-f-1-23-4-56-78-9-eee'
    

    Alternative: use awesome-slugify  package.

Sorting

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

    1import operator
    2
    3[dict(a=1, b=2, c=3), dict(a=2, b=2, c=2), dict(a=3, b=2, c=1)].sort(
    4    key=operator.itemgetter("c")
    5)
    

Date & Time

I recommend using Arrow . But if you can’t, here are some pure-python snippets.

  • Add a month to the current date:

    1import datetime
    2import dateutil
    3
    4datetime.date.today() + dateutil.relativedelta(months=1)
    

Network

  • Set urllib2 timeout ( source  ):

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

    1$ python -m SimpleHTTPServer 8000
    

Debug

  • Add a Python’s debugger break point:

    1import pdb
    2
    3pdb.set_trace()
    
  • Delete all .pyc and .pyo files in the system:

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

Version

  • Print Python’s 3-elements version number:

    1$ python -c "from __future__ import print_function; import sys; print('.'.join(map(str, sys.version_info[:3])))"
    22.7.6
    
  • Compare Python version for use in shell scripts:

    1$ python -c "import sys; exit(sys.version_info[:3] < (2, 7, 9))"
    2$ if [[ $? != 0 ]]; then
    3>     echo "Old Python detected.";
    4> fi
    5Old Python detected.
    

Style

  • Use autopep8 to apply PEP8’s coding style on all Python files:

    1$ find ./ -iname "*.py" -print -exec autopep8 --in-place "{}" \;
    

Configuration

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

Package Management

  • Generate a binary distribution of the current package:

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

    1$ python ./setup.py register sdist bdist_egg bdist_dumb upload
    
  • Download Pygments’ source distribution from PyPi, without dependencies ( source  ):

    1$ pip download --no-binary=:all: --no-deps pygments==2.14.0
    
  • Hackish way to execute the CLI above with Pip’s internal (tested with pip==22.1 ), inspired by pip._internal.cli.base_command.Command._main()  :

     1from pathlib import Path
     2
     3from pip._internal.cli.status_codes import SUCCESS
     4from pip._internal.commands.download import DownloadCommand
     5from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
     6
     7
     8tmp_path = Path("/tmp")
     9
    10# Emulate the following CLI call:
    11#   $ pip download --no-binary=:all: --no-deps pygments==2.14.0
    12cmd = DownloadCommand(name="dummy_name", summary="dummy_summary")
    13
    14with cmd.main_context():
    15    cmd.tempdir_registry = cmd.enter_context(tempdir_registry())
    16    cmd.enter_context(global_tempdir_manager())
    17    options, args = cmd.parse_args([
    18        "--no-binary=:all:",
    19        "--no-deps",
    20        "--dest",
    21        f"{tmp_path}",
    22        f"pygments==2.14.0",
    23    ])
    24    cmd.verbosity = options.verbose
    25    outcome = cmd.run(options, args)
    26    assert outcome == SUCCESS
    27
    28package_path = tmp_path.joinpath("Pygments-2.14.0.tar.gz")
    29assert package_path.is_file()
    

Jinja

To generate curly braces:

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

Data