Pontakorn Paesaeng
Pontakorn's Blog

Pontakorn's Blog

4 things you can do to make your Python code better

Photo by Greg Rosenke on Unsplash

4 things you can do to make your Python code better

Pontakorn Paesaeng's photo
Pontakorn Paesaeng
·Dec 25, 2021·

3 min read

Table of contents

  • 1. Follow PEP 8 convention.
  • 2. Use formatter and linter.
  • 3. Include documentation with docstring and type hints.
  • 4. Review your code.

Imagine that you were working on a project yesterday and you cannot understand your code today. Or, someone wrote a long line of code and you need to fix it. But you cannot because you do not understand the code at all. If these things happen, that could mean the code is bad.

There are many definitions of good code. In this post, good code is understandable, simple, and standard. These qualities will be explained in 4 tips to make your Python code better. These tips can be applied to other languages as well with different tools and convention.

1. Follow PEP 8 convention.

PEP 8 is official guideline for writing Python code. It primarily focuses on readability and consistency such as how to name a variable. Using PEP8 will make code easier to read and understand. Let's take a look at this example.

def getinformationfromshop(shopname):
    # Insert logic here
   return information

You can see it's difficult to read. Better names are getInformationFromShop, GetInformationFromShop, or get_information_from_shop. In PEP8, words should be separated by underscore. The first name is for Java and the second name is for C#. Also, in the second case, it might be mistaken for class instead. The better code looks like this.

def get_information_from_shop(shop_name):
    # Insert logic here
   return information

You can see that it looks better now. Many built-in functions in Python also follow the same convention. There are exceptions for legacy code such as logging module, which is ported from log4j. PEP8 should not be followed if it breaks compatibility.

2. Use formatter and linter.

In PyCharm, there is a built-in formatter. It can fix many issues such as inconsistent spacing or unnecessary parenthesis. Not everything can be fixed with PyCharm auto formatter.

If you are not using PyCharm, you can use other formatters such as black or autopep8 as well.

Other things are covered by linters. Linter is a program that check quality of your code. It can detect some bad things such as unused variables or methods that could be standalone functions.

pylint and flake8 are popular linters for Python.

3. Include documentation with docstring and type hints.

Good code often explains itself. But sometimes it is not enough. That's why we have documentation and docstring. Take a look at this code.

def get_all_links(src):
    # Insert logic here.
    return all_links

It is ambiguous. What is src? What is returned? Now, I add docstring.

def get_all_links(src: str) -> List[str]:
    """Return all hyperlink in the webpage.

    This function will perform HTTP request and fetch all hyperlinks if the page is HTML.

    Args:
        src: URL of the page ex. https://blog.pontakorn.dev
    Returns:
        All hyperlinks in the given page    
    Raises:
        ValueError: If the given page is not HTML
    """
    # Insert logic here
    return all_links

Now, we know that we need to input URL, the function will make a HTTP request, and all hyperlinks are returned. We also know required type.

mypy is a progam for static type checking for Python. You can try it.

4. Review your code.

Try to guess what does this code do.

if x - 6 > 0:
    return True
else if x - 6 <= 0:
    return False

3...2...1...0 The code is comparing if x is greater than 6 or not. You can see that the code is unnecessary complex. It can be just

return x > 6

It sounds ridiculous but it can happen to you time to time especially when you forgot to sleep or don't have enough coffee. Take a break and come back to your code to review.

I hope these 4 tips will help you improve your Python code.

 
Share this