Code Style

Erik Tollerud (STScI)

Why do we care about style?

  • It helps you read your code
Environsarcmin=DEGREEs(v/(1000*dMPC))*60
sc =sKyCoO(ra*U.deg,dec*U.deg,frame='icrs')

vs.

environs_arcmin = degrees(value_in_kpc / (1000 * distance)) * 60
sc = SkyCoord(ra*u.deg, dec*u.deg, frame='icrs')
  • It helps others read your code, even if they don't know what it's for
  • It satisfied those of us who have a pathological need for consistency
  • BUT: "A Foolish Consistency is the Hobgoblin of Little Minds"

    -Emerson... and GvR

Code style in Python

https://www.python.org/dev/peps/pep-0008/

  • Used by almost every significant Python project (with some perturbations).

PEP8 Important Elements

Indentation

  • Indentation should always be 4 spaces

Capitalization/naming conventions

  • Don't use 1- or 2-letter variable names.
  • CamelCase : class names
  • snake_case : packages, modules, functions
  • (jamitalltoegether: variables)
  • If you need a variable that's a built-in, use a trailing underscore: if_ = 10 (but also probably just don't do this)
  • A lot more detail in PEP8... ~half of its length

Operators and function call spacing

  • Use spaces after function calls: call_this(a, b, c)
  • Use spaces around operations: c = a + b not c=a+b
  • Official Exception: function defaults: def function(a=1, b=3)
  • Informal exception: * or / don't need spaces because of math: y = m*x + b

Imports

  • Should be at the top of the file
  • Should be individual imports:
    import os
    import sys
    not
    import os, sys
  • Put stdlib at top, others after
  • Alternative: "pyramid" style
    import os
    import sys
    import numpy as np
    import some_really_long_package_name

Use underscores for "private"

  • self._this_is_private
  • self.__this_is_extra_private (this actually does something, too)

Comments

  • Inline comments should always have >=2 spaces before, 1 space after: c = a + b # important comment here
  • Generally: use docstrings over comments when possible. There's a whole PEP (PEP257) about docstring formats
  • "Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language."

Line lengths

  • Lines should not be longer than 79 chars. Can make this practical with Python's parenthesis-driven line continuation:
    function(with, some, arguments)
    is the same as
    function(with,
           some,
           arguments)
a + very + long +expression / that(goes + a + bit longer + than + 80, 
                                   characters + so + we + have + to + think)

(This is the most controversial guideline...)