Python Development Guide: a selection of best practices

Source: Internet
Author: User

Python Development Guide: a selection of best practices

General principles

Value

  • "Develop tools you want to use for others ." -- Kenth Reitz

  • "Conciseness is always better than availability. "-- Pieter Hintjens

  • "Meets 90% of application scenarios. Ignore those who say no. "-- Kenth Reitz

  • "Beauty is better than ugliness. "-- PEP 20

  • Developed for open-source or closed-source projects.

General development principles

  • "Being clear is better than being implicit ." -- PEP 20

  • "Easy to read is also priced ." -- PEP 20

  • "Everyone can install patches ." -- Khan College Development document

  • Fix the problem immediately once it finds a broken window design error, a wrong decision, or a low coding quality.

  • "Do it better than not do it now ." -- PEP 20

  • "The test should be thorough. Write New Function documentation. "

  • Human-driven development is more important than test-driven development. Translator: the original article Even more important that Test-Driven Development -- Human-Driven Development. The translator thinks that more important that should be more important than. It should be the author's mistake. Otherwise, it cannot be understood ,)

  • These principles may be -- probably -- changed.

Special rules

Style

If it feels reasonable, it should follow PEP 8.

Name

  • Variables, functions, methods, packages, modules

  • Lowercase letters and underlines are used to separate the words lower_case_with_underscores)

  • Class, exception

  • Capital CapWords)

  • Protected methods and internal functions

  • _ Single_leading_underscore (self,...) Starting with an underscore ,...))

  • Private Method

  • _ Double_leading_underscore (self,...) starting with a double underline ,...))

  • Constant

  • All uppercase letters, which are separated by underlines (ALL_CAPS_WITH_UNDERSCORES)

General naming rules

Do not use variable names with only one letter, for example, l, I, O ).

Exception: in a very short code block, if the meaning of the variable name can be clearly viewed from the context, you can.

No problem

For e in elements:
E. mutate ()

Avoid repeated variable names.

Correct practice

Import audio

Core = audio. Core ()
Controller = audio. Controller ()

Incorrect practice

Import audio

Core = audio. AudioCore ()
Controller = audio. AudioController ()

"Reverse mark" is better.

Correct practice

Elements =...
Elements_active =...
Elements_defunct =...

Incorrect practice

Elements =...
Active_elements =...
Defunct_elements...

Avoid using the getter and setter methods.

Correct practice

Person. age = 42

Incorrect practice

Person. set_age (42)

Indent

Use four space characters-never use Tab characters. That's all.

Module reference

Reference the entire module, rather than a single identifier in the module. For example, assume that there is a sessions. py file under a cantee module,

Correct practice

Import canteen
Import canteen. sessions
From canteen import sessions

Incorrect practice

From canteen import get_user # Symbol from canteen/_ init _. py
From canteen. sessions import get_session # Symbol from canteen/sessions. py

Exceptions: If the third-party code documentation clearly specifies a single reference, you can.

Reason: Avoid circular references. Here.

Place the reference part of the Code on the top of the file and divide it into three parts in the following order. Each part has a blank line. 1. System Reference 2. Third-party reference 3. Local reference

Reason: Clearly shows the reference sources of each module.

Document

Complies with the document string principles proposed by PEP 257. ReStructuredText (reST) and Sphinx help ensure that documents comply with standards.

For functions with obvious functions, write a line of document strings.

"Returns the pathname of ''foo ."""

Multi-line document strings should include:

  • One line Abstract

  • Describe use cases if appropriate

  • Parameters

  • Returns data types and semantics unlessNone

    "Train a model to distinguish between Foo and Bar.

    Usage ::

    >>> Import klassify
    >>> Data = [("green", "foo"), ("orange", "bar")] >>> classifier = klassify. train (data)

    : Param train_data:(color, label)Form a ancestor list.

    : Rtype: A: class:Classifier <Classifier>

    """

Note:

Use the active word "return") instead of the descriptive word "Return Value "). In the document string of the class__init__Method To write the document.

Class Person (object ):
"A simple representation of a human being.: param name: A string, the person's name.: param age: An int, the person's age. "def _ init _ (self, name, age): self. name = name self. age = age

Comments

Use as few as possible. Instead of writing many comments, it is better to improve code readability. Generally, short methods are more effective than annotations.

Incorrect practice

# If the sign is a stop sign
If sign. color = 'red' and sign. sides = 8:
Stop ()

Correct practice

Def is_stop_sign (sign ):
Return sign. color = 'red' and sign. sides = 8

If is_stop_sign (sign ):
Stop ()

But when writing comments, remember: "follow the style elements written by Stoke and white." -- PEP 8

Length of each line

Do not care too much. It's okay to use 80 to 100 characters.

Use parentheses to continue the current row.

Wiki = (
"The Colt Python is a. 357 Magnum caliber revolver formerly manufactured"
"By Colt's Manufacturing Company of Hartford, Connecticut. It is sometimes"
'Referredto as a "Combat Magnum". It was first introduced in 1955,'
"Same year as Smith & Wesson's M29. 44 Magnum ."
)

Test

Try to test all the code as much as possible, but do not stick to coverage.

General test criteria

  • Use a long descriptive name. Generally, this avoids writing documents in the test method.

  • Tests should be isolated. Do not interact with real databases or networks. Use a separate test database to destroy the database after testing, or use a simulated object.

  • Use factory mode instead of fixture.

  • Do not pass the incomplete test. Otherwise, you may forget it. You should add some placeholder statements, suchassert False, "TODO: finish me".

Unit Test

  • Focus on a small feature each time.

  • The running speed is faster, but the speed is slower than the test speed.

  • Generally, each class or model should have a test case class.

    Import unittest
    Import factories

    Class PersonTest (unittest. TestCase ):

    Def setUp (self ):
    Self. person = factories. PersonFactory ()

    Def test_has_age_in_dog_years (self ):
    Self. assertEqual (self. person. dog_years, self. person. age/7)

Function Testing

Function Testing is a high-level test, which is closer to how end users interact with applications. It is usually used for testing network applications and graphics applications.

  • Write a test according to the scenario. The name of the test case should look like the scenario description.

  • Note the specific scenario information before writing the code.

    Import unittest

    Class TestAUser (unittest. TestCase ):

    Def test_can_write_a_blog_post (self ):
    # Goes to the her dashboard
    ...
    # Clicks "New Post"... # Fills out the post form... # Clicks "Submit"... # Can see the new post...

Note that the class name of the test case is put together with the name of the test method, just like "test whether a user can publish a blog post ".

This article is inspired by the following materials...

  • PEP 20 (The Zen of Python)

  • PEP 8 (Style Guide for Python)

  • The Hitchiker's Guide to Python

  • Khan Academy Development Docs

  • Python Best Practice Patterns

  • Pythonic Sensibilities

  • The Pragmatic Programmer

  • And many other materials

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.