程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The importance of Python programming specification and software development catalog specification

編輯:Python

List of articles

  • 1 The importance of programming specifications
    • 1.1 notes
      • Python Special notes in
    • 1.2 Canonically named variables :
      • 1.2.1 Variable definition rules :
      • 1.2.2 Variable specification naming considerations :
      • 1.2.3 General naming rules :
    • 1.3 Typesetting problem
      • 1.3.1 Code layout :
      • 1.3.2 Document layout :
      • 1.3.3 Use of space :
    • 1.4 other
  • 2. The importance of software development catalog specification
    • 2.1 Why design a good directory structure ?
    • 2.2 How the catalog is organized
    • 2.3 README Project description document
      • 2.3.1 Why write README file ?
      • 2.3.2 complete README Included content
      • 2.3.3 A simple template
      • 2.3.4 canonical README How to write a document ?
    • 2.4 About requirements.txt and setup.py
      • 2.4.1 setup.py
      • 2.4.2 requirements.txt
        • 2.4.2.1 generation
        • 2.4.2.2 Loading mode
    • 2.5 About how to use configuration files

1 The importance of programming specifications

1.1 notes

Each comment is marked with a pound sign (#) Start , Until the end of the line , Until the end of the line . We can put anything in the comments , because Python Will completely ignore their existence . Here are the next few rules :
(1) Suppose the reader's Python The level is the same as you ( for instance , Don't explain “ What is a string ” , Don't explain “ What is an assignment statement ”)
(2) Don't comment on meaningless things .
(3) Many programmers will write something on the code with **“ TODO ” perhaps “ FIXME ”** Comments at the beginning , The purpose is to remind them to come back and write or clean up some unfinished problems .
(4) If you need to think hard when writing a program , Comments should be written , In the future, others will not rack their brains in this place . In particular , If you use key points to describe when developing programs or writing functions , Try to write carefully , After the development work is completed , You should also keep all the original points and explain them directly .
(5) Again , If a bug It's hard to find out , Or its modification scheme is more complex , Then you should write a note to explain it . If not , Then in the future, programmers of other complex parts of the code may decide that they don't need to be so complex and change it to the original , So that your efforts will be wasted .
(6) If you need a lot of comments to explain the function of a piece of code , Then we should sort out these codes , such as , If you need to separate the 15 A list to explain , Then the function should be split into smaller code blocks , Only a few smaller lists are processed every other time .
(7) Outdated comments are better than no comments , So after modifying a piece of code , Be sure to check the relevant comments , And make appropriate modifications to ensure that it can still accurately describe the function of the code .
(8) The more comments, the better , Make the whole code full of comments , But rarely see code , This distorts the meaning of the note .

Python Special notes in

such as :Python There is a line stating python Single line comments in encoded format . This line of comment specifies that the file is utf-8 code . This line of special comments can only be placed at the first line or beginning of the file .

#_*_coding:utf-8_*_

Another is to explain that the scripting language is python Of , Is to use /usr/bin The following procedure ( Tools )python, This interpreter , To explain python Script , To run the python The script .

#!/usr/bin/python

1.2 Canonically named variables :

1.2.1 Variable definition rules :

(1) Variable names can only be letters , Any combination of numbers or underscores
(2) The first character of a variable name cannot be a number
(3) Keyword cannot generate variable name

1.2.2 Variable specification naming considerations :

(1) Variable name cannot be too long
(2) Variable nouns do not reach the meaning
(3) The variable name is Chinese , pinyin

1.2.3 General naming rules :

(1) Try to use lowercase letters alone ‘l’, Capital ‘O’ Wait for confusing letters .
(2) Module naming should be as short as possible , Use all lowercase , You can use underscores .
(3) Package naming should be as short as possible , Use all lowercase , Underline is not allowed .
(4) Class naming uses CapWords The way , The class used inside the module uses _CapWords The way .
(5) Exception naming uses CapWords+Error Suffix mode .
(6) Global variables are only valid in modules , similar C In language static. There are two ways to do this , One is __all__ Mechanism ; Second, prefix with an underscore .
(7) Function names are all lowercase , You can use underscores .
(8) Constant names are all uppercase , You can use underscores .
(9) Attributes of a class ( Methods and variables ) Name in all lowercase , You can use underscores .
(10) The properties of the class are 3 Species scope public、non-public and subclass API, Can be interpreted as C++ Medium public、private、protected,non-public Before attributes , Prefix with an underscore .
(11) If the property of the class conflicts with the keyword name , Suffix one underline , Try not to use abbreviations or other methods .
(12) To avoid naming conflicts with subclass properties , Before some properties of the class , Prefix two underscores . such as : class Foo In a statement __a, During the interview , Only through Foo._Foo__a, Avoid ambiguity . If the subclass is also called Foo, There's nothing we can do .
(13) The first parameter of a class's method must be self, The first parameter of a static method must be cls.

1.3 Typesetting problem

1.3.1 Code layout :

(1) Indent .4 Indent of spaces ( Editor can complete this function ), Don't use Tap, Not to mention mixing Tap And Spaces .
(2) Maximum length per line 79, You can use backslash to wrap lines , It's best to use parentheses . The newline point should be followed by a carriage return .
(3) Classes and top-level Two empty lines between function definitions ; A blank line between method definitions in a class ; Empty line between logical independent paragraphs in a function ; Try not to be empty in other places .

1.3.2 Document layout :

(1) The order of module content : Module description and docstring—import—globals&constants— Other definitions . among import part , According to the standard 、 The three parties and their own writing order are in turn , A blank line between .
(2) Don't in one sentence import Multiple libraries in , such as import os, sys Not recommended .
(3) If the from XX import XX Reference Library , It can be omitted ‘module.’, There may be naming conflicts , At this time, we should adopt import XX.

1.3.3 Use of space :

General principles , Avoid unnecessary spaces
(1) Don't put spaces before all kinds of closing brackets .
(2) comma 、 The colon 、 No spaces before semicolons .
(3) Don't put a space before the opening bracket of a function . Such as Func(1).
(4) Don't put a space before the left bracket of the sequence . Such as list[2].
(5) Add a space to the left and right of the operator , Don't add spaces for alignment .
(6) The default parameter of the function uses the assignor to omit the space around .
(7) Don't write multiple sentences on the same line , Although the use of ‘;’ allow .
(8) if/for/while In the sentence , Even if the execution statement has only one sentence , There has to be another line .

1.4 other

(1) Other things are taken into account in the coding python Efficiency of implementation , For example, operators ‘+’ stay CPython(Python) Medium efficiency is very high , All are Jython But very low , So we should adopt .join() The way .
(2) Use as much as possible ‘is’‘is not’ replace ‘==’, such as if x is not None Is better than if x.
(3) Use class based exceptions , Each module or package has its own exception class , This exception class inherits from Exception.
(4) Do not use naked... In exceptions except,except Heel specific exceptions.
(5) In the abnormal try As little code as possible . such as :

try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
*** be better than ***
try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)

(6) Use startswith() and endswith() To check the sequence prefix or suffix instead of slice . such as :

if foo.startswith('bar'):
*** be better than ***
if foo[:3] == 'bar':

(7) Use isinstance() Compare types of objects . such as

if isinstance(obj, int):
*** be better than ***
if type(obj) is type(1):

(8) Judge whether the sequence is empty or not , There are the following rules

if not seq:
if seq:
*** be better than ***
if len(seq)
if not len(seq)

(9) Don't end a string with spaces .
(10) Binary data judgment uses if boolvalue The way

2. The importance of software development catalog specification

2.1 Why design a good directory structure ?

Let's design a clear directory structure , To achieve the following two points :
① High readability : People who are not familiar with the code of this project , You can understand the directory structure at a glance , Know which program startup script is , Where is the test catalog , Where is the configuration file and so on . In order to understand the project very quickly .
② High maintainability : After defining the rules of organization , The maintainer will know exactly , What new files and code should be placed in what Directory . The advantage is , as time goes on , Code / The scale of the configuration increases , There will be no confusion in the project structure , Still well organized .

2.2 How the catalog is organized

Suppose your project is called foo, I suggest the most convenient directory structure, which is enough :

Foo/
|-- bin/
| |-- foo
|
|-- foo/
| |-- tests/
| | |-- init.py
| | |-- test_main.py
| |
| |-- init.py
| |-- main.py
|
|-- docs/
| |-- conf.py
| |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README

among :
bin/: Store some executable files of the project , Of course, you can name it script/ Or something like that .
foo/: Store all the source code of the project .① All the modules in the source code 、 All packages should be in this directory . Don't put it in the top-level Directory .② Its subdirectory tests/ Store unit test code ; ③ The entry to the program is best named main.py.
docs/: Store some documents .
setup.py: install 、 Deploy 、 Packaged scripts .
requirements.txt: Store the external information that the software depends on Python Package list .
README: Project description document .
besides , There are some scenarios that offer more . such as LICENSE.txt,ChangeLog.txt Documents, etc. , I'm not listed here , Because these things are mainly used when the project is open source .

2.3 README Project description document

2.3.1 Why write README file ?

The purpose of this document is to briefly describe the information of the project , Let readers quickly understand the project .

2.3.2 complete README Included content

(1) It needs to explain the following :

Software positioning , The basic functions of the software .
How to run the code : Installation environment 、 Start command, etc .
Brief instructions for use .
Code directory structure description , More detailed point can explain the basic principle of the software .
FAQ .

Two , It includes the following contents :

Name of the project and all sub modules and libraries ( For new users , Sometimes different names can lead to confusion )
For all projects , And descriptions of all submodules and Libraries
How to use 5-line code( If it is a library )
Copyright and licensing information ( Or a reading permit )
Grab document instructions
install 、 Instructions for configuring and running programs
Grab the latest code and instructions for building them ( Or a quick overview and 「 read Install」)
Author list or 「Read AUTHORS」
Submit bug, Functional requirements , Submit patch , Join the mailing list , To be informed of , Or join the introduction of users or development zone groups
Other contact information ( E-mail address , Website , Corporate name , Address, etc )
A brief history ( change , Replace or other )
A legal statement

2.3.3 A simple template

Of course , What we wrote earlier , Don't bother so much , Just write a few simple and necessary things , For example, legal statements , Contact records, etc , There is no need to write .

########### Environment depends on node v0.10.28+ redIs ~

########### Deployment steps

  1. Add system environment variable
    export $PORTAL_VERSION=“production” // production, test, dev

  2. npm install // install node Running environment

  3. gulp build // Front end compilation

  4. Start two configurations ( has forever For example )
    eg: forever start app-service.js
    forever start logger-service.js

########### Directory structure description ├── Readme.md // help ├── app // application ├── config // To configure │ ├── default.json │
├── dev.json // development environment │ ├── experiment.json //
experiment │ ├── index.js // Configuration control │ ├── local.json
// Local │ ├── production.json // Production environment │ └── test.json
// Test environment ├── data ├── doc // file ├── environment
├── gulpfile.js ├── locales ├── logger-service.js // Start log configuration
├── node_modules ├── package.json ├── app-service.js //
Start application configuration ├── static // web Static resource loading │ └── initjson │
└── config.js // Configuration provided to the front end ├── test ├── test-service.js └──
tools

###########V1.0.0 Version content update

  1. new function aaaaaaaaa
  2. new function bbbbbbbbb
  3. new function ccccccccc
  4. new function ddddddddd

2.3.4 canonical README How to write a document ?

For common use windows My classmates , How to write README Well ?
Need to use MarkDown

This website can be written directly MarkDown Language
Markdown The official tutorial

2.4 About requirements.txt and setup.py

2.4.1 setup.py

Generally speaking , use setup.py To manage code packaging 、 install 、 Deployment issues . The industry standard is to use Python Popular packaging tools setuptools To manage these things . This approach is widely used in open source projects . But the core idea here is not to use standardized tools to solve these problems , But rather , A project must have an installation and deployment tool , It can quickly and conveniently install the environment on a new machine 、 Deploy the code and run the program .

Installation environment 、 Deployment code 、 Running the program is all done manually , Problems encountered :
① When installing the environment, you often forget to add a new one recently Python package , As soon as it's online , The program went wrong .
②Python Version dependence of packages , Sometimes we use one version of the program Python package , But the official package is up to date , By manual installation, it may be wrong .
③ If you rely on a lot of packages , It's time-consuming to install these dependencies one by one .
④ When new students start writing projects , It's very cumbersome to run the program , Because you may often forget how to install various dependencies .
setup.py You can automate these things , Increase of efficiency 、 Reduce the probability of error ." Complex things, automation , What can be automated must be automated ." It's a very good habit .

An example :

from setuptools import setup
# Metadata goes in setup.cfg. These are here for GitHub's dependency graph.
setup(
name="Flask",
install_requires=[
"Werkzeug >= 2.0",
"Jinja2 >= 3.0",
"itsdangerous >= 2.0",
"click >= 8.0",
"importlib-metadata >= 3.6.0; python_version < '3.10'",
],
extras_require={

"async": ["asgiref >= 3.2"],
"dotenv": ["python-dotenv"],
},
)

Of course , Simply write your own installation script (deploy.sh) replace setup.py Not too bad .

2.4.2 requirements.txt

The purpose of this file is :
① It is convenient for developers to maintain the package dependence of software . Add new packages added in the development process to this list , To avoid the setup.py Missing package when installing dependency .
② It's convenient for readers to know what is used in the project Python package .

The format of this file is that each line contains a description of the package dependency , Usually flask>=0.10 This format , The requirement is that this format can be pip distinguish , So it's easy to go through pip install -r requirements.txt Let's take all the Python All the packages are loaded .

2.4.2.1 generation

(1) pip freeze > requirements.txt
In this way, a requirements.txt file , The current python All packages owned in the environment , And the version of the package . It can be regarded as pip list Everything displayed by this command is recorded . This way is fast , however requirements.txt The package contained in the file is all the packages in the current environment , If you do not use the current project package will also be included .
(2) pipreqs Directory path
This method needs to be passed first pip install install pipreqs modular .
pip install pipreqs
Navigate to the root directory of your project , perform
pipreqs ./ --encoding=utf8
It's added here –encoding=utf8 To avoid garbled code . This will also generate requirements.txt file , However, the package version contained in this file is the version information of all packages used in the current project .

2.4.2.2 Loading mode

We from github A project was cloned on , We can do it according to its requirements.txt Configuration environment , Recommend conda Create a new environment and then use the following command .
pip install -r requirements.txt

2.5 About how to use configuration files

Be careful , In the directory structure above , No will conf.py Put it in the source directory , It's on the docs/ Under the table of contents .
Many projects use configuration files as :
The configuration file is written in one or more python In file , Like here conf.py.
Which module in the project uses this configuration file directly through import conf Use configuration in code in this form .
I don't quite agree with this approach :
This makes unit testing difficult ( Because the module is internally dependent on external configuration )
On the other hand, the configuration file acts as the interface of the user control program , It should be free for the user to specify the path to the file .
The reusability of program components is too poor , Because this kind of hard coding runs through all modules , Make most modules depend on conf.py This file .
therefore , I think the use of configuration , A better way is to ,
Modules can be configured flexibly , Not affected by external configuration files .
The configuration of the program can also be controlled flexibly .
What supports this idea is , Used to nginx and mysql All of my classmates know that ,nginx、mysql These programs are free to specify user configuration .
therefore , It shouldn't be directly in the code import conf To use the configuration file . In the directory structure above conf.py, Is a configuration example given , It's not writing configuration files that are directly referenced in the program . You can give main.py The startup parameter specifies the configuration path so that the program can read the configuration content . Of course , there conf.py You can change a similar name , such as settings.py. Or you can use other formats to write configuration files , such as settings.yaml And so on. .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved