Several conventions help you write cool Python code

Tram Ho

Hello everyone, today I would like to introduce some convention to help you write more beautiful Python code, or by calling Python programmers: Pythonic.

The official Python code writing standard is PEP 8 (Python Enhancements Proposal8) 0- style guide. These standards are quite a lot, I summarize below some typical standards as follows:

1. Line spacing and indentation

You should use 4 spaces in each indent layer. If your line is too long (> 79 or> 119 characters depending on where), you can split it into more lines. Note that elements that are carriage return should be arranged vertically with the elements on the line above:

For example:

It’s correct

Wrong

You can also add 4 space characters (equivalent to one more indent) to distinguish parameters from other elements in the function.

It’s correct

Wrong

2. Using Tab or Space?

In Python, Space (space) takes precedence. Tab mark should be used in cases where the code has already used Tab. * Note: Python 3 does not allow to use Tab and Space mixed in the same file.

3. Line break before or after operator?

This is actually still controversial, but some Python programmers prefer a newline after the operator to match the mathematical representations:

4. Blank line

You should wrap the definition of def and Class with the above parts with two blank lines, and the methods in Class should have one empty line apart.

5. Import

Each line should only import 1 library.

For example:

It’s correct:

Wrong:

However, if you import 2 sub-modules from a library, you can import in one line.

import statements should be placed at the beginning of the file, before you declare modules and variables / constants.

You should group import statements in the following order:

  1. Standard libraries like os, sys
  2. 3rd party libraries
  3. Local modules / libraries

6. Use spaces

You should avoid extra spaces in the following situations:

  • Right inside brackets.

It’s correct:

Wrong:

  • After the comma and before the closing parenthesis

It’s correct:

Wrong:

  • Immediately before a comma, semi-colon, or two dots

It’s correct:

Wrong:

Only one space is required for each variable assignment

It’s correct:

Wrong:

7. Naming way

  • The Class and Exception names should capitalize every first letter of the word

  • Function and variable names should be lowercase and separate words with _

  • Constant names should be all capitalized

Those are some of the most basic conventions that will help you write Python code, thanks for your reading. We will return to this topic in a future article. If you want, you can read more here .

Share the news now

Source : Viblo