coding_best_practices_2020-06-03
coding_best_practices_2020-06-03
Practices
Daniel Perrefort – University of Pittsburgh
Best practices are any procedure that is
accepted as being the most effective either
by consensus or by prescription.
Guide for
Well written code conveys
Python Code professionalism.
import json
import os
__version__ = 0.1
def my_function():
...
PEP 8: Naming Conventions
TYPE NAM ING CO NVENT IO N EX AM P L ES
Variable Use lowercase letters or word, or words separated with x, var, my_variable
underscores. (I.e., snake_case)
Class Start each word with a capital letter. Do not separate words with Model, MyClass
underscores. (I.e., CamalCase)
Constant Use an uppercase single letter, word, or words separated by CONSTANT, MY_CONSTANT
underscores.
Module Use short lowercase words separated with underscores. module.py, my_module.py
# Wrong # Correct
if foo == None: if foo is not None:
do_something() do_something()
# Also wrong
if not foo is None:
do_something()
PEP8: General Recommendations
Always use a `def` statement instead of an assignment statement for
anonymous (lambda) expressions
# Wrong # Correct
f = lambda x: 2 * x def double(x):
return 2 * x
PEP8: General Recommendations
Derive exceptions from `Exception` rather than `BaseException`
Use explicit exception catching (avoid bare exceptions)
Keep `try` statements as simple as possible
# Wrong # Correct
try: try:
import platform_specific_module import platform_specific_module
my_function()
except ImportError:
except: platform_specific_module = None
platform_specific_module = None
else:
my_function()
PEP8: General Recommendations
Booleans are already Booleans – they don’t need comparisons
For sequences, (e.g., a lists), use the fact that empty sequences are false
# Worse:
if my_boolean is True:
do_something()
# Still bad:
if len(my_list) != 0:
do_something()
If You Take Away One Thing...
Command line tools for PEP 8 are also available Side Note
Pylint: http://pylint.pycqa.org/
Flake8: https://flake8.pycqa.org/
Jupyter Plugins:
Python Black: https://github.com/drillan/jupyter-black
Documentation is key to reusable code
Docstring
Documentation can include technical
Conventions notes and derivations.
def kos_root():
"""Return the pathname of the KOS root directory."""
...
PEP257: Multi-Line Docs
Start with a single line docstring
Include additional documentation as necessary
Always document arguments and returns
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
Returns:
An imaginary number corresponding to the given arguments
"""
External Style Guides (Google)
Based on the principle that docs in the code should be human readable
def connect_to_next_port(minimum):
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
http://google.github.io/styleguide/pyguide.html
Document the Code AND the Project
Organize
Version control provides continuity and
Your Project collaboration
source Your project source code. The code responsible for performing your analysis.
scripts Individual scripts responsible for running separate stages of your analysis.
F IL E US AG E
LICENSE.txt License for the distribution of your code (or the forked source). (GNU)
The Infamous “Scripts” Directory
Scripts should NOT be where your analysis logic is
Clone repo located at <r epo> onto local machine. Original repo can be Rebase t he current branch ont o <base> . <base> can be a commit ID,
gi t cl one <r epo> gi t r ebase <base>
located on t he local filesystem or on a remote machine via HTTP or SSH. branch name, a t ag, or a relat ive reference t o HEAD.
gi t conf i g Define aut hor name t o be used for all commit s in current repo. Devs Show a log of changes t o t he local reposit ory’s HEAD.
gi t r ef l og
user . name <name> commonly use - - gl obal flag t o set config opt ions f or current user. Add - - r el at i ve- dat e flag t o show dat e info or - - al l t o show all refs.
gi t add St age all changes in <di r ect or y> for t he next commit .
<di r ect or y> Replace <di r ect or y> w it h a <f i l e> t o change a specific fil e. GIT BRANCHES
gi t commi t - m Commit t he st aged snapshot , but inst ead of launching List all of t he branches in your repo. Add a <br anch> argument t o
gi t br anch
" <message>" a t ext edit or, use <message> as t he commit message. creat e a new branch w it h t he name <br anch> .
gi t checkout - b Creat e and check out a new br anch named <br anch> .
gi t st at us List w hich fil es are st aged, unst aged, and unt racked.
<br anch> Drop t he - b flag t o checkout an exist ing branch.
Display t he ent ire commit hist ory using t he def ault format .
gi t l og gi t mer ge <br anch> Merge <br anch> int o t he current branch.
For cust omizat ion see addit ional opt ions.
gi t r emot e add Creat e a new connect ion t o a remot e repo. Aft er adding a remot e,
UNDOING CHANGES <name> <ur l > you can use <name> as a short cut for <ur l > in ot her commands.
gi t r ever t Creat e new commit t hat undoes all of t he changes made in gi t f et ch Fet ches a specific <br anch> , from t he repo. Leave off <br anch>
<commi t > <commi t > , t hen apply it t o t he current branch. <r emot e> <br anch> t o fet ch all remot e refs.
Remove <f i l e> from t he staging area, but leave t he w orking directory Fet ch t he specified remot e’s copy of current branch and
gi t r eset <f i l e> gi t pul l <r emot e>
unchanged. This unst ages a file w it hout overw rit ing any changes. immediat ely merge it int o t he local copy.
Show s w hich fil es w ould be removed from w orking direct ory. gi t push Push t he branch t o <r emot e> , along w it h necessary commit s and
gi t cl ean - n
Use t he - f flag in place of t he - n flag t o execut e t he clean. <r emot e> <br anch> object s. Creat es named branch in t he remot e repo if it doesn’t exist .
Visit at lassian.com /git for m ore inform at ion, t raining, and t ut orials
Virtual Environments
Use a different environment for each project
$ conda deactivate
Conclusions