Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python for Geeks

You're reading from   Python for Geeks Build production-ready applications using advanced Python concepts and industry best practices

Arrow left icon
Product type Paperback
Published in Oct 2021
Publisher Packt
ISBN-13 9781801070119
Length 546 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Muhammad Asif Muhammad Asif
Author Profile Icon Muhammad Asif
Muhammad Asif
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Section 1: Python, beyond the Basics
2. Chapter 1: Optimal Python Development Life Cycle FREE CHAPTER 3. Chapter 2: Using Modularization to Handle Complex Projects 4. Chapter 3: Advanced Object-Oriented Python Programming 5. Section 2: Advanced Programming Concepts
6. Chapter 4: Python Libraries for Advanced Programming 7. Chapter 5: Testing and Automation with Python 8. Chapter 6: Advanced Tips and Tricks in Python 9. Section 3: Scaling beyond a Single Thread
10. Chapter 7: Multiprocessing, Multithreading, and Asynchronous Programming 11. Chapter 8: Scaling out Python Using Clusters 12. Chapter 9: Python Programming for the Cloud 13. Section 4: Using Python for Web, Cloud, and Network Use Cases
14. Chapter 10: Using Python for Web Development and REST API 15. Chapter 11: Using Python for Microservices Development 16. Chapter 12: Building Serverless Functions using Python 17. Chapter 13: Python and Machine Learning 18. Chapter 14: Using Python for Network Automation 19. Other Books You May Enjoy

Developing an effective naming scheme

If developing and implementing the right logic in code is science, then making it pretty and readable is an art. Python developers are famous for paying special attention to the naming scheme and bringing The Zen of Python into it. Python is one of the few languages that have comprehensive guidelines on the naming scheme written by Guido van Rossum. They are written in a PEP 8 document that has a complete section on naming conventions, which is followed by many code bases. PEP 8 has naming and style guidelines that are suggested. You can read more about it at https://www.Python.org/dev/peps/pep-0008/.

The naming scheme suggested in PEP 8 can be summarized as follows:

  • In general, all module names should be all_lower_case.
  • All class names and exception names should be CamelCase.
  • All global and local variables should be all_lower_case.
  • All functions and method names should be all_lower_case.
  • All constants should be ALL_UPPER_CASE.

Some guidelines about the structure of the code from PEP 8 are given here:

  • Indentation is important in Python. Do not use Tab for indentation. Instead, use four spaces.
  • Limit nesting to four levels.
  • Remember to limit the number of lines to 79 characters. Use the \ symbol to break long lines.
  • To make code readable, insert two blank lines to separate functions.
  • Insert a single black line between various logical sections.

Remember that PEP guidelines are just suggestions that may be customized by different teams. Any customized naming scheme should still use PEP 8 as the basic guideline.

Now, let's look in more detail at the naming scheme in the context of various Python language structures.

Methods

Method names should use lowercase. The name should consist of a single word or more than one word separated by underscores. You can see an example of this here:

calculate_sum

To make the code readable, the method should preferably be a verb, related to the processing that the method is supposed to perform.

If a method is non-public, it should have a leading underscore. Here's an example of this:

_my_calculate_sum

Dunder or magic methods are methods that have a leading and trailing underscore. Examples of Dunder or magic methods are shown here:

  • __init__
  • __add__

It is never a good idea to use two leading and trailing underscores to name a method, and the use of these by developers is discouraged. Such a naming scheme is designed for Python methods.

Variables

Use a lowercase word or words separated by an underscore to represent variables. The variables should be nouns that correspond to the entity they are representing.

Examples of variables are given here:

  • x
  • my_var

The names of private variables should start with an underscore. An example is _my_secret_variable.

Boolean variables

Starting a Boolean variable with is or has makes it more readable. You can see a couple of examples of this here:

class Patient:
    is_admitted = False
    has_heartbeat = False

Collection variables

As collections are buckets of variables, it is a good idea to name them in a plural format, as illustrated here:

class Patient:
    admitted_patients = ['John','Peter']

Dictionary variables

The name of the dictionary is recommended to be as explicit as possible. For example, if we have a dictionary of people mapped to the cities they are living in, then a dictionary can be created as follows:

persons_cities = {'Imran': 'Ottawa', 'Steven': 'Los Angeles'}

Constant

Python does not have immutable variables. For example, in C++, we can specify a const keyword to specify that the variable is immutable and is a constant. Python relies on naming conventions to specify constants. If the code tries to treat a constant as a regular variable, Python will not give an error.

For constants, the recommendation is to use uppercase words or words separated by an underscore. An example of a constant is given here:

CONVERSION_FACTOR

Classes

Classes should follow the CamelCase style—in other words, they should start with a capital letter. If we need to use more than one word, the words should not be separated by an underscore, but each word that is appended should have an initial capital letter. Classes should use a noun and should be named in a way to best represent the entity the class corresponds to. One way of making the code readable is to use classes with suffixes that have something to do with their type or nature, such as the following:

  • HadoopEngine
  • ParquetType
  • TextboxWidget

Here are some points to keep in mind:

  • There are exception classes that handle errors. Their names should always have Error as the trailing word. Here's an example of this:
    FileNotFoundError
  • Some of Python's built-in classes do not follow this naming guideline.
  • To make it more readable, for base or abstract classes, a Base or Abstract prefix can be used. An example could be this:
    AbstractCar
    BaseClass

Packages

The use of an underscore is not encouraged while naming a package. The name should be short and all lowercase. If more than one word needs to be used, the additional word or words should also be lowercase. Here's an example of this:

mypackage

Modules

When naming a module, short and to-the-point names should be used. They need to be lowercase, and more than one word will be joined by underscores. Here's an example:

main_module.py

Import conventions

Over the years, the Python community has developed a convention for aliases that are used for commonly used packages. You can see an example of this here:

import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels as sm
import matplotlib.pyplot as plt 

Arguments

Arguments are recommended to have a naming convention similar to variables, because arguments of a function are, in fact, temporary variables.

Useful tools

There are a couple of tools that can be used to test how closely your code conforms to PEP 8 guidelines. Let's look into them, one by one.

Pylint

Pylint can be installed by running the following command:

$ pip install pylint

Pylint is a source code analyzer that checks the naming convention of the code with respect to PEP 89. Then, it prints a report. It can be customized to be used for other naming conventions.

PEP 8

PEP 8 can be installed by running the following command:

 pip: $ pip install pep8

pep8 checks the code with respect to PEP 8.

So far, we have learned about the various naming conventions in Python. Next, we will explore different choices for using source control for Python.

You have been reading a chapter from
Python for Geeks
Published in: Oct 2021
Publisher: Packt
ISBN-13: 9781801070119
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime