Skip to content

Instantly share code, notes, and snippets.

@seanjensengrey
Last active March 13, 2016 05:18
Show Gist options
  • Save seanjensengrey/a08910b0d204b037c2ba to your computer and use it in GitHub Desktop.
Save seanjensengrey/a08910b0d204b037c2ba to your computer and use it in GitHub Desktop.

Basic opinionated Python code technique guide. For lower level naming and structure, see https://github.com/amontalenti/elements-of-python-style

Don't overuse the batteries

Install deps with pip managed by virtualenv, this decouples the VM from the runtime. Try not to target the latest VM release, this prevents your code from being trivially installable on existing Ubuntu and Centos systems. Use tox and py.test (see below) to confirm that decoupling.

namedtuple

Immutable, named lightweight composite containers for your data. Removes magic numbers from your code.

In [1]: from collections import namedtuple

In [2]: namedtuple?
Signature: namedtuple(typename, field_names, verbose=False, rename=False)
Docstring:
Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__                   # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22)             # instantiate with positional args or keywords
>>> p[0] + p[1]                     # indexable like a plain tuple
33
>>> x, y = p                        # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y                       # fields also accessable by name
33
>>> d = p._asdict()                 # convert to a dictionary
>>> d['x']
11
>>> Point(**d)                      # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
File:      ~/x.env/lib/python3.5/collections/__init__.py
Type:      function

PyCharm

No Python editor or IDE comes close in terms of refactoring support and code navigation. The free (beer and speech) Community Edition is very usable.

Virtualenv

Manage per project virtual environments that are sandboxed off from the system Python with virtualenv

py.test and tox

Investigate using pyenv to install arbitrary major.minor.point releases of Python and test inside of tox

Program in a Functional Style

PDB

Learn how to debug your Python code

import pdb

pdb.set_trace()

When talking to native code, use cffi

https://cffi.readthedocs.org/en/latest/

It allows for portable extensions across PyPy, CPython and Jython.

@ganprad
Copy link

ganprad commented Mar 13, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment