Writing high-quality code-suggestions for improving python programs (2), high-quality python

Source: Internet
Author: User

Writing high-quality code-suggestions for improving python programs (2), high-quality python

The original Article is published on my blog homepage. For more information, see the source!

Recommendation 7: Use the assert statement to discover problems
Assert exists in many languages and is mainly used for debugging programs. It can quickly and conveniently check program exceptions or detect inappropriate input to prevent unexpected situations. The syntax is as follows:

assert expression1 ["," expression2]

The value of expression1 returns True or False, and AssertionError is triggered when the value is False. expression2 is optional and is often used to transmit specific exception information.

However, assertions have a price, which will have a certain impact on the performance. For compiled languages such as C/C ++, this may not be so important, this is because assertions are only enabled in debug mode. However, python does not strictly define the differences between debugging and release modes. assertions are designed to capture user-defined constraints rather than program errors, therefore, pay attention to the following points during use:

  • Do not abuse it. if an exception is caused by an assertion, it usually indicates a bug in the program. Therefore, the assertion should always be true in a place where the normal logic cannot be reached or under normal circumstances.
  • If python exceptions can be handled, do not use assertions. We do not recommend using assertions for errors such as array out-of-bounds, Type mismatch, and Division 0.
  • Do not use assertions to check user input
  • After a function is called, you can use assertions to check whether the returned values are reasonable.
  • Assertions can be used when the condition is a prerequisite for continued business logic

Recommendation 8: Intermediate variables are not recommended for data exchange values.
In python, the more pythonic method for implementing numerical exchange is:

 
x,y = y,x

In terms of execution efficiency and code conciseness, this value exchange is very advantageous. Python expressions are generally calculated from left to right, but when an expression is assigned a value, the right operand of the expression is calculated prior to the left operand. Therefore, for the above expression, the execution sequence in the memory is as follows:

1. Calculate the expression y and x on the right. Therefore, create the ancestor (y, x) in the memory)
2. calculate and assign values to the left of the expression. The ancestor is assigned to the identifier on the left, unpacking, and the first identifier of the ancestor is y) assign the first element (x) to the left, and the second element is similar, so as to exchange the x and y values.

Recommendation 9: Make full use of the features of Lazy evaluation
Lazy evaluation is often translated as "delayed computing" or "inert computing". It refers to calculating the value of the expression only when it is actually needed. There are two advantages:

  • Avoid unnecessary computation and improve performance. For example, if the first item is false, the computation will not be followed.
  • Saves space and makes the Infinite Loop Data Structure possible. In python, the most typical example of using latency computing is the generator expression, which generates the required elements through yield only each time it needs to be calculated. For example, in the Fibonacci series, while True is not an infinite loop.
def fib():    a, b = 0, 1    while True:        yield a        a, b = b, a+b

 

Recommendation 10: Understand the defects of enumeration substitution
1. Use class attributes

class Seasons:    Spring, Summer, Autumn, Winter=range(4)

2. Use Functions

def enum(*posarg, **keysarg):    return type("Enum", (object,), dict(zip(posarg, xrange(len(posarg))), **keysarg))Seasons = enum("Spring", "Summer", "Autumn", Winter=1) 

3. Use collections. namedtuple

Seasons = namedtuple(‘Seasons’, ‘Spring Summer Autumn Winter’)._make(range(4))

Recommendation 11: type is not recommended for type check.
The built-in function type (object) is used to return the type of the current object. Therefore, you can compare it with the name defined in the types module of python and determine whether the variable type is required to be signed based on the return value. For example, you can use the following code to determine whether a variable a is of the list type:

if type(a) is types.ListType:

The names of all basic types can be found in the types module, such as types. BooleanType, types. IntType, types. StringType, and types. DictType. But why is it not recommended to use type for variable type check.

  • First, we find that user-defined types extended based on built-in types (such as int) cannot accurately return results.
  • In classical classes, the type () returned by any class instance is the same. In this case, type () is used () function to determine whether the two variable types are the same. Obviously, the results are different from what we understand. So in order to constrain the user's input type to make it consistent with the expected type, if the type has a corresponding factory function, you can use the factory function to convert the type, such as list (listing) and str (name. Otherwise, you can use the isinstance () function for detection, as shown below:
Isinstance (object, classinfo) # Where classinfo can be a direct or indirect class name, basic type name, or a ancestor composed of them # isinstance (2, float) false # isinstance ("a", (str, unicode) True

Suggested 12: Convert to floating point type as much as possible before starting
When Division operations are involved, convert the operands to the floating point type before performing operations. For example:

a = float(4*3)/float(12*7)

However, python3 does not have this problem. You can use the following statement to remove integer division.

from __future__ import division

In addition, pay attention to the processing of floating point numbers. The calculation results may not be completely accurate.

Summary: programming languages are usually used in a conventional way. It is necessary to master these idioms described above. If the calculation requires a high accuracy, you can use decimal for processing or extend the floating point number to an integer as much as possible, and then convert it back after the calculation is complete. At the same time, it is best to specify the accuracy of the Floating Point Number comparison.

Reference: Writing high-quality code-91 suggestions for improving python programs

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.