The world’s leading publication for data science, AI, and ML professionals.

Python Beginner Breakthroughs (Pythonic Style)

As it's been said, code is read way more times than it is written. Developing good formatting habits while writing code is almost as…

Photo by Jordan Koons on Unsplash
Photo by Jordan Koons on Unsplash

The primary function for code is to work, the second is to make it interpretable if you have plans to use it more than once. Developing good habits and following the general recommended formatting practices that are presented in PEP-8 (found here) is an easy and quick way to standardizing the appearance of your code. PEP-8 (Python Enhancement Proposal #8) was created as a means to try and create a template of common practices for the purpose of enhancing readability and standardization. In this article, I’ll highlight some of the changes that you can make to your code to make it functional and stylish.


Code Lay-Out

Indentation

PEP-8 provides extensive guidelines on when and how indentation should be appropriately used. I’ll highlight two cases that might not be inherently intuitive to the newbie coder.

  • Tabs or spacing – Python 3 takes care of this issue of mixing tabs and spacing, but in theory, spaces are the preferred method of indentation, but tabs are appropriate if it’s already consistently used in an existing code.
  • Max line Length – Limit any line of long and complex code to 79 characters. This is more for aesthetics and to also allow you to maximize screen space for other windows of your IDE. Docstrings and Comments should be limited to 72 characters.
  • Line Breaks in relation to Operators – This is actually something that will make understanding code much simpler once you look and compare the difference, but line-breaks should be inserted before an operator, look at the code block below. The first example is when the line break is before and the second is after. The second approach makes understanding the expression much simpler from a visual perspective as it is comparable to handwriting an arithmetic problem.
total_cost = (retail price + 
              total_taxes +
              shipping_handling -
              discount)
# Preferred option
total_cost = (retail price 
              + total_taxes
              + shipping_handling
              - discount)

Imports

Try to utilize absolute imports as much as possible to make the code more readable and to also enable the reader to understand which modules are coming from which libraries. If the second part is less critical or common modules within a library are used it is ok to import the modules from the library exclusively.

  • Only import one library at a time. (The only exception would be to call multiple modules from an imported library in one line as seen below)
#Good only calling a single library
import statistics
#exception for multiple modules
from scipy import optimize, stats

Whitespaces

As is written in PEP-8, excessive whitespaces can just be rough on the eyes and make having to go back and make fixes/corrections a little more time-consuming.

  1. Directly following an opened parenthesis:
  2. Between trailing common and closed parenthesis
  3. Before commas, semicolon, or colon
  4. Note that in slices of sequential data types the colon acts like an operator. You should treat the colon with equal space on both sides of it (see examples below)
  5. Immediately before an open parenthesis of a function call
  6. Additional spaces to align an assignment to another
1. spam(ham[1], {eggs: 2}) # Good
   spam( ham[ 1 ], { eggs: 2 } ) # Bad
2. foo = (0,) # Good
   bar = (0, ) # Not so good
3. if x == 4: print x, y; x, y = y, x # Thumbs up!
   if x == 4 : print x , y ; x , y = y , x # Ewww!
4. ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:] # Good
   ham[lower+offset : upper+offset] # Good too
   ham[1: 9], ham[1 :9], ham[1:9 :3] # Ouch
   ham[lower : : upper] # Eyes hurting
5. spam(1) # Good
   spam (1) # Why??
6. x = 1
   y = 2
   long_variable = 3 # Good
   x             = 1 # Excessive spaces in code block
   y             = 2
   long_variable = 3

The key to whitespaces is to use them only as needed. Notice above how much extra space is created by unnecessary whitespaces. Don’t go overboard and ensure that the clarity and flow of the code aren’t broken up.

Photo by Austin Distel on Unsplash
Photo by Austin Distel on Unsplash

Comments

I’m personally against using a ton of comments in a code unless you are explicitly writing it for someone to learn from it. Variable assignment, function development, and everything else in your code should have readability instilled for someone with Coding experience to understand what is going on. That is not to say that there shouldn’t be any comments, but rather (like whitespaces) use them as necessary. For example, when something may not be evidently apparent to a subsequent reader of the code.

  • Update the comments as the code is modified (A must!!!)
  • Comments should be complete sentences for readability
  • Paragraphs inside block comments should be separated by a line starting with #
  • Inline comments should be avoided as they usually are deemed unnecessary and distracting.

Naming Styles

When you assigning names to items in your code the below examples are commonly accepted forms:

b (single lowercase letter)
B (single uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CapWords, CamelCase5, StudlyCaps)
mixedCase (differs from CapitalizedWords by initial lowercase character!)
Capitalized_Words_With_Underscores (ugly!)

Add-Ins

There are a wide variety of add-ins that you can install into your IDE environment that will make suggestions and/or auto-correct your code as per PEP-8 and other formatting standards. One that I use is called PyLint, but there are many other similar add-ins available.


Hopefully, this little note on coding style will help make your code more concise and more importantly easier to read! Any comments or feedback is much appreciated and if you have anything you’d like explored more please leave a response to this article.


Related Articles