Python Function design principles

Source: Internet
Author: User
Tags value of pi

In any programming language, the use of functions is mainly due to the following two scenarios:

    • code block duplication, it is necessary to consider the use of functions to reduce the redundancy of the program
    • code block is complex, this time you can consider the use of functions, enhance the readability of the program

when the process is complex enough, consider the functions and how to combine them. in Python function design, mainly considering the function size, aggregation, coupling three aspects, these three should be attributed to the scope of planning and design. High cohesion and low coupling are the general principles of any language function design.

    • How to break down a task into a more targeted function that leads to aggregation
    • How to design the communication between functions is also related to the coupling
    • How to design the size of a function to enhance its polymerization and reduce its coupling

" Aggregation "

    • Each function only does one thing

Perfect programming, each function should and only do one thing.

For example: Put an elephant in the refrigerator in three steps: Open the door, put the elephant in, and close the door.

you should write three functions instead of a function to do all the work. This structure is clear, hierarchical, well understood!


" size "

    • Keep it simple and keep it short

Python is a process-oriented language and an object-oriented language, but more of a role as a scripting language.

The same functionality, using Python to implement its code length may be 1/3 of languages such as C/c++/java. Hundreds of lines of code will be able to achieve a small function!

If a function designed in the project needs to be paged to finish, consider splitting the function.

In more than 200 modules of Python's own, it is rare to see a function with two or three pages.

Python code is known for its simplicity, and a function that is too long or deeply nested often becomes a symptom of design flaws.


" coupling "

    • Input using parameters, output using return statement

Doing so allows the function to be independent of what is outside of it. Parameters and return statements are the best way to isolate external dependencies.

    • Use global variables with caution

The first consideration: global variables are often a way of communicating between crappy functions.

It can cause problems with dependencies and timing, which can lead to difficulties in debugging and modifying the program.


Second consideration: from code and performance optimizations, local variables are much faster than global variables.

Based on the order in which Python searches for variables: local function variable = = " Upper function variable = =" global variable = = " built-in variable "

As can be seen from the above, local variables are first searched, and once found, this stops. The following tests were done specifically to test the results as follows:

Import Profilea = 5def param_test (): B = 5 Res = 0 for i in range (100000000): res = B + I return res If __name__== ' __main__ ': Profile.run (' param_test () ') >>> ===================================== RESTART = = = ==================================>>> 5 function calls in 37.012 seconds #全局变量测试结果: Notoginseng s Ordered by:s   Tandard name Ncalls tottime percall cumtime percall Filename:lineno (function) 1 19.586 19.586 19.586 19.586:0 (range) 1 1.358 1.358 1.358 1.358:0 (setprofile) 1 0.004 0.004 35.448 35.448    <string>:1 (<module>) 1 15.857 15.857 35.443 35.443 learn.py:5 (param_test) 1 0.206 0.206 37.012 37.012 profile:0 (param_test ()) 0 0.000 0.000 profile:0 (Profiler) &GT;&GT;&G T ===================================== RESTART =====================================>>> 5 function calls    In 11.504 seconds#局部变量测试结果: 11s Ordered by:standard name ncalls tottime percall cumtime percall Filename:lineno (function) 1 3.135 3.135 3.135 3.135:0 (range) 1 0.006 0.006 0.006 0.006:0 (setprofile) 1 0.0 XX 0.000 11.497 11.497 <string>:1 (<module>) 1 8.362 8.362 11.497 11.497 learn.py:5 (par          am_test) 1 0.000 0.000 11.504 11.504 profile:0 (param_test ()) 0 0.000 0.000 Profile:0 (Profiler)

    • Avoid changing variable type parameters

Python data types such as lists and dictionaries belong to mutable objects. When passed as a parameter to a function, it is sometimes modified as if it were a global variable.

The disadvantage of this is that the coupling between functions is enhanced, resulting in a function that is too special and unfriendly. Maintenance is also difficult.

It's time to consider using slice s[:] and copy () and deepcopy () functions in the Copy module to make a copy to avoid modifying mutable objects

Refer to this article: a detailed copy of the depth of Python

    • Avoid directly changing variables in another module

For example, in the b.py file to import a module, A has variable pi = 3.14, but b.py want to modify it to: pi = 3.14159, where you can't figure out exactly what the value of the variable pi was originally. In this case, you might consider using an easy-to-understand function name:

#模块a. PyPI = 3.14def setpi (new):    pi = new    return pi
this has the value of the pi that you want, and does not change the value of pi in the A module .
Import API = A.SETPI (3.14159) Print Pi;a.pi




Python Function design principles

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: [email protected] 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.