Basic opinionated Python code technique guide. For lower level naming and structure, see https://github.com/amontalenti/elements-of-python-style
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.
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
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.
- https://www.jetbrains.com/pycharm/
- https://www.youtube.com/results?search_query=pycharm
- JetBrainsTV https://www.youtube.com/watch?v=IHui8nBJiW0&list=PLQ176FUIyIUY5Ii58pzoZhS_3qIBL80nz
Manage per project virtual environments that are sandboxed off from the system Python with virtualenv
Investigate using pyenv
to install arbitrary major.minor.point releases of Python and test inside of tox
- https://github.com/yyuu/pyenv
- https://github.com/yyuu/pyenv-virtualenv
- https://github.com/samstav/tox-pyenv
- Stop Writing Classes, https://www.youtube.com/watch?v=o9pEzgHorH0
- Use
namedtuple
- list comprehensions, generator expressions
- Only mutate an existing structure when you have to, create new stuff, drop references to old
- Use
sorted
,reversed
(returns new data) - Have more than 3 args? consider naming them, https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments
- Use decorators to separate concerns
Learn how to debug your Python code
import pdb
pdb.set_trace()
https://cffi.readthedocs.org/en/latest/
It allows for portable extensions across PyPy, CPython and Jython.
http://pbpython.com/plateau-of-productivity.html
This is a great blog post.