Python

A programming language whose remarkable feature is working how you imagine, if not how it should

A Swiss army knife of coding tools. Good matrix library, general scientific tools, statistics tools, web server, art tools, but, most usefully, interoperation with everything else - It wraps C, C++, Fortran, includes HTTP clients, parsers, API libraries, and all the other fruits of a thriving community. Fast enough, easy to debug, garbage-collected. If some bit is too slow, you compile it, otherwise, you relax. A good default if you’d rather get stuff done than write code.

I typically do my stats and graphs in R, my user interface in javascript, my linear algebra library is fortran, and I use julia for my other scientific calculations, but python is the thread that stitches this Frankensteinisch monster together.

Of course, it could be better. clojure is more elegant, scala is easier to parallelise, julia prioritises science more highly…

But in terms of using a well-supported language that goes on your computer right now, and requires you to reinvent few wheels, and which is transferable across number crunching, web development, UIs, text processing, graphics and sundry other domains, and does not require heavy licensing costs, this one is a good starting point.

What a pitch! Now, let’s look closer and see all the horrid things that are wrong with it.

Debugging, profiling and testing

See Python debugging, profiling and testing.

ipython, the interactive python upgrade

The python-specific part of jupyter, which can also run without jupyter. Long story.

The main thing I forget here is…

Pretty display of objects

Check out the rich display protocol which allows you to render objects as arbitrary graphics. Some examples of how to use that are helpful. How to use this? The display api docs explain that you should implement methods on your objects such as, e.g., _repr_svg_.

This was what I used to create latex_fragmentwhich can display arbitrary latex inline. This is how you use it:

def _figure_data(self, format):
    fig, ax = plt.subplots()
    ax.plot(self.data, 'o')
    ax.set_title(self._repr_latex_())
    data = print_figure(fig, format)
    # We MUST close the figure, otherwise
    # IPython’s display machinery
    # will pick it up and send it as output,
    # resulting in double display
    plt.close(fig)
    return data

# Here we define the special repr methods
# that provide the IPython display protocol
# Note that for the two figures, we cache
# the figure data once computed.

def _repr_png_(self):
    if self._png_data is None:
      self._png_data = self._figure_data('png')
    return self._png_data

For a non-graphical non-fancy terminal, you probably simply want nice formatting of big data structures.

from pprint import pprint, pformat
# display it
pprint(obj)
# get a formatted representation
pretty = pformat(obj)

What? You want to write your own pretty-printer, with correct indentation? Use tiles.

Pro tip: dotenv

dotenv allows easy configuration through OS environment variables or text files in the parent directory. You should probably use this. PRO-TIP: there are lots of packages with similar names. Make sure you install using this one

pip install python-dotenv

String formatting

String formatting things that are unnecessarily hard to discern from the manual

What a nightmare is that manual for the string formatting. While all the information you need is in there, it is arranged in perverse inversion of some mixture of the frequency and the priority with which you use it. See Marcus Kazmierczak’s cookbook instead.

Highlights:

## float precision
>>> print("{:.2f}".format(3.1415926))
3.14
## left padding
>>> print("{:0>2d}".format(5))
05

## power tip which the manual does not make clear:
## variable formatting of variable formatting
>>> pi = 3.1415926
>>> precision = 4
>>> print( "{:.{}f}".format( pi, precision ) )
3.1415

f-strings

f-strings make things somewhat easier for python 3.6+ because they don’t need to mess around with naming things for the .format(foo=foo) call:

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."

Timestamps

Why is a now timestamp in UTC not the first line in every academic research workbook/paper/data analysis? Because it’s tedious to look up the different bits.

Here you go:

from datetime import datetime
datetime.utcnow().isoformat(timespec='seconds')

Rendering HTML output

You have a quick and dirty chunk o’ HTML you need to output? You aren’t writing some damnable webapp with a nested hierarchy of template rendering and CSS integration into some design framework? You just want to pump out some markup?

I recommend yattag which is fast, simple, good and has a 1-page manual. It works real good.

Rendering markdown as HTML

from markdown import markdown
html_string = markdown("""
# Title

Paragraph. *emphasis*.
""")

Compiling and FFI

see Accelerating python.

Packaging and environments

Not so hard, but confusing and chaotic due to many long-running disputes only lately resolving.

General

Anaconda

The distribution you use if you want to teach a course in numerical python without dicking around with a 5 hour install process.

Download e.g. Linux x64 Miniconda, from the download page.

bash Miniconda3-latest-Linux-x86_64.sh
# login/logout here
conda config --set auto_activate_base false # don't be so aggressive conda
conda init fish  # fish users

Has a slightly different packaging workflow. See, e.g. Tim Hoppper’s workflow which explains this environment.yml malarkey, or the creators’ rationale.

The upshot for the end user is that if you want to install something with tricky dependencies like ViTables, you do this:

conda install pytables=3.2
conda install pyqt=4

Aside: Do you use fish shell? You need to do some extra setup. Specifically, add the line

source (conda info --root)/etc/fish/conf.d/conda.fish

into ~/.config/fish/config.fish.

NB Conda will fill up your hard disk if not regularly disciplined. via conda clean.

conda clean -pt

You might also want to not have the gigantic MKL library installed, of which I am in any case not a fan. You can usually disable it per request:

conda create -n pynomkl python nomkl

between the various versions and install MKL alone was using about 10GB total on my mac when I last checked Reducing the harm of this kind of nonsense is one reason I only ever install the minimalist miniconda as my base anaconda distribution, cautiously adding things as I need them.

venv

venv is now a built-in python virtual environment system in python 3. It doesn’t support python 2 but fixes various problems, e.g. it supports framework python on macOS which is important for GUIs, and is covered by the python docs in the python virtual environment introduction. It has a higher-level, er, …wrapper (?) called pipenv.

# Create venv
python3 -m venv ~/.virtualenvs/learning_gamelan_keras_2
# Use venv from fish
source ~/.virtualenvs/learning_gamelan_keras_2/bin/activate.fish
# Use venv from bash
source ~/.virtualenvs/learning_gamelan_keras_2/bin/activate

Python environment management management

One suggestion I’ve has is to use pyenv. which eases and automates switching between all the other python environments created by virtualenv, python.org python, os python, anaconda python etc.

BUT WHO MANAGES THE VIRTUALENV MANAGER MANAGER?

Asynchrony in python

See asynchronous python.

Watching files for changes

Does this inotify solution work for non-Linux? Because macOS uses FSEvents and Windows uses I-don’t-even-know.

watchdog asserts that it is cross-platform. (source)

Python 2 vs 3

Are you old? New to python 3?

Sebastian Raschka, The key differences between Python 2.7.x and Python 3.x with examples

Neat python 3 stuff

Alex Rogozhnikov, Python 3 with pleasure highlights some new tricks which landed recently.

Useful for me is a friendlier python struct-like thing, the data class Geir Arne Hjelle explains.

You can override module accessors.

Asynchrony is less awful.

Python 2 and 3 compatibility

TL;DR: I am no employee of giant enterprise-type business with a gigantic legacy code base, and so I don’t use python 2. My code is not python 2 compatible. Python 3 is more productive, and no-one is paying me to be less productive right now. Python 2 code is usually easy to port to python 3. It is possible to write code which is compatible with python 2 and 3, but then I would miss out on some of the work that has gone into making python 3 easier and better, and waste time porting elegant easy python 3 things to hard boring python 2 things.

🏗 six versus future.

Typing

Python 3.6+ includes type hinting, and projects such as mypy support static analysis using type hints. There are not yet many tutorials on the details of this. Here’s one.

Short version: you go from this:

def fib(n):
  a, b = 0, 1
  while a < n:
    yield a
    a, b = b, a+b

to this:

def fib(n: int) -> Iterator[int]:
  a, b = 0, 1
  while a < n:
    yield a
    a, b = b, a+b

However, if I am going to that much trouble, I would in fact rather julia, which takes type-hinting further, using it to JIT-compile optimised code.

Command line parsers

Another bike-shedding danger zone is command-line parsing, leading to the need to spend too much time parsing command line parsers rather than parsing command lines.

  • argparse is built-in to python stdlib and is OK, so why not just use that and avoid other dependencies? Answer: a dependency you might already have is likely to have introduced another CLI parsing library.

  • Hydra is a framework for elegantly configuring complex applications”

    Builds CLIs with autocomplete and other fun stuff.

  • Click

    is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box.

    • arbitrary nesting of commands
    • automatic help page generation
    • supports lazy loading of subcommands at runtime

    Aims to offer an alternative to the built-in argparse, which they regard as excessively magical. Its special feature is setuptools integration enabling installation of command-line tools from your current ipython virtualenv.

  • Invoke

    provides a clean, high level API for running shell commands and defining/organizing task functions from a tasks.py file it offers advanced features as well – namespacing, task aliasing, before/after hooks, parallel execution and more.

  • argh was/is a popular extension to argparse

    Argh is fully compatible with argparse. You can mix Argh-agnostic and Argh-aware code. Just keep in mind that the dispatcher does some extra work that a custom dispatcher may not do.

  • clip.py comes with a passive-aggressive app name, (+1) is all about wrapping generic python commands in command-line applications easily, much like click.

Miscellaneous stuff I always need to look up

Progress meters

tqdm seems to be a de facto standard.

Also works in jupyter. Install it:

> pip install ipywidgets
> jupyter nbextension enable --py widgetsnbextension
> jupyter labextension install @jupyter-widgets/jupyterlab-manager

Use it:

%%capture
from tqdm import tqdm_notebook as tqdm
tqdm().pandas()

# Only this last bit is needed outside jupyter
with tqdm(total=len(my_list)) as pbar:
    for x in my_list:
        pbar.update(1)

Misc recommendations

  • Pext is a python extension to script handy things in a handy GUI.
  • Let’s get weird: Hy is a lisp that compiles to python syntax trees