Fast Python: 5 Best Practices to more Pythonic Code

Fast Python: 5 Best Practices to more Pythonic Code

Often computer science students graduate without knowing the best programming practices and standards used in the software industry. That results in shit code and horror stories, resulting in embarrassment and often jokes.

Along with git knowledge about different tools, having some kind of information about best practices can give you an edge when you apply for an internship or your first job.

One of Guido’s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, “Readability counts”.

I am going to be sharing 5 simple rules for writing production-level Python code.

Proper use of Blank Lines

Surround top-level function and class definitions with two blank lines.

Method definitions inside a class are surrounded by a single blank line.

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Use blank lines in functions, sparingly, to indicate logical sections.


# Add two blank lines before each function or class definition
def myfunc(a,b):
 
 # Add a blank line before every if statement
 if a > b:
 print(“Hello World”)
 
 # Add a blank line before every return statement
 return a,b
        

Descriptive Naming Styles

There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.

The following naming styles are commonly distinguished:

  • b (single lowercase letter)
  • B (single uppercase letter)
  • lowercase
  • lower_case_with_underscores
  • UPPERCASE
  • UPPER_CASE_WITH_UNDERSCORES
  • CapitalizedWords (or CapWords, or CamelCase — so named because of the bumpy look of its letters). This is also sometimes known as StudlyCaps. Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
  • mixedCase (differs from CapitalizedWords by initial lowercase character!)
  • Capitalized_Words_With_Underscores (ugly!)

Imports

Imports should usually be on separate lines:

Correct:


import os
import sys        

Wrong:


import sys, os        

It’s okay to say this though:

Correct:


from subprocess import Popen, PIPE        

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

Imports should be grouped in the following order:

  • Standard library imports.
  • Related third-party imports.
  • Local application/library-specific imports.

Prescriptive Naming Conventions

Global Variable Names

(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via from M import * should use all mechanism to prevent exporting globals or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are “module non-public”).

Function and Variable Names

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Function and Method Arguments

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

DRY Principle

The DRY or “Don’t Repeat Yourself” principle is a software development practice aimed at reducing the repetition of information.

Popularized by the book, The Pragmatic Programmer, the DRY principle states that, “every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” Using the principle, logic or algorithms that have certain functionality should only appear once in an application.

To view or add a comment, sign in

More articles by Abdullah N.

  • Best JavaScript MOOCs according to Reddit in 2023

    As I begin my software engineering career, I am on the hunt for the best JavaScript tutorials and courses. And, being…

  • Review: My 2 years at Arbisoft

    As I complete 2 years at Arbisoft, here is what I learned during that time with a few ups and down. Arbisoft's culture…

    19 Comments
  • Scrapy 101: Architecture and Lifecycle

    Scrapy (/ˈskreɪpaɪ/) is an application framework for crawling websites and extracting structured data which can be used…

  • Slowly but surely getting over my fear of failure and programming

    I spent 3 days consecutively on HackerRank solving easy to medium problems without being scared of failure. Here is my…

    4 Comments

Others also viewed

Explore content categories