Python code style - discussion

Discussion created by curtvprice Champion on Oct 5, 2012
Latest reply on Oct 9, 2012 by mhoyland
I strongly recommend the Python style guide. It has many great examples on how to write (or not write) python code.

PEP 8 -- Style Guide for Python Code

This community may do well to promote its own style guide with respect to writing and documenting script tools.

Hey Esri teams, do you have a style guide? It appears that different groups hew to different standards at this point, for example compare the python scripts in the Geostatistical toolbox to Feature Class To Geodatabase.

To get folks thinking:

1. When should we add complexity by wrapping the tool in a function (if __name__=="__main__" etc)?
2. We are developing best practices, and we should try to promote them. For example:
  (a) Use feature layer instead of a feature class parameters if possible - to support things like selected sets and pick lists of open layers in ArcMap
  (b) Place optional parameters toward the end of argument lists if possible (critical when using "obtained from" in parameter validation
  (c) Use a trailing "s" for cursor and list variables ("for fc in fcs","for row in rows")
  (d) Use "with" when creating currsors, or "try ... finally" with a del to ensure they are closed no matter what to avoid file lock problems.
  (d) When to use ## vs #?  (I use ## for debug code)
4. Any examples, thoughts of unit testing concepts applied to ArcGIS script tool development?

Two more thoughts:

1. As many users of script tools (myself included) are not sophisticated developers, I think it's important to hew to simplicity ("Keep it simple, stupid!") -- but avoiding making the code so bonehead it is less understandable and reusable ("Keep it simple stupid" --the comma matters!).

2. I thought quote (from PEP8) is especially relevant for us writing Python script tools:
One of Guido's key insights is that code is read much more often than it is written

Amen I say.