In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what is the correct posture of document-oriented programming for Python developers. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Overview
Qin people have no time to mourn themselves, but future generations mourn it; posterity mourns but does not learn from it, and also makes posterity mourn posterity!-- on the importance of document-oriented programming
If you want to see the ability to recognize a person's ability to write code, comments are actually a significant dividing line between veteran drivers and young fresh meat (have you ever observed that the leaders of your company are basically in meetings or writing documents). Usually, the ratio of the amount of documentation to the amount of code for the old driver is 1:1, while the newcomers often think that the task can be completed after writing the functional module. In the production environment, we need to face a large number of complex business logic and data checking and docking with all parties, the document quality and code quality will be promoted to the same level. Many people are not in the habit of writing comments, most of them are not lazy, on the one hand, they do not realize the benefits of writing documents, and on the other hand, they do not understand the tools in this area. After all, relying on human initiative in management is far less effective than relying on tools. This article introduces tips on how to use Python comments to improve the quality and efficiency of document writing.
Python
In actual production, machine learning now looks like the job of an algorithm engineer during the day and becomes operation and maintenance + testing at night. Python has always been favored by test engineers and operation and maintenance engineers. Here are a few classic annotations to use case.
Write unit tests with comments: doctest
Unit testing is an essential part of code development, and it is very important for Bug positioning and code quality. Now the most well-known unit testing framework is Unittest, which draws on the JUnit of the mature unit testing framework in Java. Even though Django has special support for this framework, it does feel verbose when implementing Unittest, setup,teardown. It often feels inadequate to maintain unit tests.
An ingenious way can be through doctest, with docstring comments to complete the unit test, because each method def is followed by a test case, followed by the code body, which makes it convenient for us to test the quality of the existing code, on the other hand, it is easy to modify.
For example:
Def factorial (n): "Return the factorial of n, an exact integer > = 0. > > [factorial (n) for n in range (6)] [1,1,2,6,24,120] > > factorial (30) 265252859812191058636308480000000 > > factorial (- 1) Traceback (most recent call last):. ValueError: n must be > = 0 Factorials of floats are OK, but the float must be an exact integer: > > factorial (30.1) Traceback (most recent call last):. ValueError: n must be exact integer > factorial (30.0) 265252859812191058636308480000000 It must also not be ridiculously large: > factorial (1e100) Traceback (most recent call last):. OverflowError: n too large "" import math if not n > = 0: raise ValueError ("n must be > = 0") if math.floor (n)! = n: raise ValueError ("n must be exact integer") if n too large 1 = = n: # catch a value like 1e300 raise OverflowError ("n too large") result = 1 factor = 2 while factor > > symbol to start a unit test Then wrap the line and enter the expected result. In fact, it is really easy to copy and paste the debugging process and results, which makes it very easy to implement TDD.
Write API documents with comments: apidoc
After we have completed the machine learning model, when we want to provide an external service interface to contribute our computing power, we need complete API documents, and it is through the call of API that we can provide a continuous stream of check data for our model, which has very practical significance to improve the effect of the model. For most people, calling API to complete development is a happy thing, because we can do a lot less work to achieve powerful functionality. However, when we need to provide API, we will face different tests, such as interface authentication, interface design, version control, concurrency problems, log burying points. These are new problems that need to be faced, and the use of apidoc can well solve many common problems in these API documents, which is equivalent to improving our interface design ability through templates.
Apidoc provides Python with a way to write API documents similar to docstring, which is syntactically similar to roxygen in R, which requires users to start with the @ xxx symbol and then write the relevant definitions and functions.
For example:
The following is a method for defining the API interface, and the core part is
Routin
GET/POST method
Name / grouping
Parameters and invocation examples
(code without use cases is a hooligan these days.)
"@ api {get} / user/:id Request User information @ apiName GetUser @ apiGroup User @ apiParam {Number} id Users unique ID. @ apiSuccess {String} firstname Firstname of the User. @ apiSuccess {String} lastname Lastname of the User."
We can go straight to an official example to learn how to use apidoc.
First, download the sample source code
Git clone https://github.com/apidoc/apidoc cd apidoc
Then, install the apidoc components
Sudo npm install apidoc-g
Next, use the official code to make an example and visit it.
Apidoc-I example/-o output/-t template/ open output/index.html
Several parameters have the following meanings:
-i:input, indicating the folder entered
-o:output, indicating the output folder
-t:template, which represents the template file. By replacing the template, we can modify the document skin.
Under the example folder, we need to fill in the configuration file in apidoc.json to define the header and footer parts of the document, and the rest of the files will automatically recognize the docstring as part of the API document.
Because the official documentation of apidoc is very simple and clear, there is not too much emphasis on syntax here.
Apidoc also provides us with the function of interface debugging. In practice, we should pay attention to:
We need a web server to use the debugging capabilities of this interface
Pay attention to cross-domain problems.
Through version comparison, we can also quickly troubleshoot changes in the API interface. It is important to note that this function requires us to save the historical documentation in the file in this directory, usually we can output the historical comments to a specific file to save.
Generally speaking, although the writing of API documents is not a very difficult thing, it can reflect the power of system module design and user experience design. We should say no those API documents without code examples and version control.
Write the command line interface with comments: docopt
With docopt, we can directly declare the parameters passed in the command line of the file in the comments, without the need to capture the input value through the argvs variable to make a judgment, which is especially useful when calling operation and maintenance scripts or several task scheduling scripts, which greatly improves the efficiency of CLI.
For example: (the code here is for reference only)
"" Usage: fiannceR.py tcp [--timeout=] fiannceR.py serial [--baud=9600] [--timeout=] fiannceR.py-h |-- help |-- version "" from docopt import docopt if _ _ name__ ='_ _ main__': arguments = docopt (_ _ doc__, version='0.1.1rc') print (arguments) fiannceR.py tcp 0.0.0.0 3838
The arguments here will send out a dictionary object that captures the input values on the command line in the form of Key-Value.
{'--baud': None,'--help': False,'--timeout': None,'--version': False,'- hype: False,': '0.0.0.09,'': '3838,' serial': False, 'tcp': True}
Summary
If you really want to roll from the data to the model and interface, then a row of annotated pictures is really unimaginably beautiful.
"" unitest > FinanceR ('20161001') 21.01 "" def FinanceR (date): price = get_price (date) return (price) class (BaseHandler): def get (self): "" apidoc @ api {get} / price/:date get the current price @ apiName GetPrice @ apiGroup Quota @ apiParam {Number} date transaction date @ apiSuccess {String} price "" date = self.get_argument ('date' None) try: price = FinanceR (date) self.write ({'data': {' price':price}, 'response': {' message':'success','code':200}}) except Exception as e: self.write ({'data':None,'response': {' message':str (e) 'code':404}}) "" Usage: fiannceR.py tcp [--timeout=] fiannceR.py serial [--baud=9600] [--timeout=] fiannceR.py-h |-- help |-- version "" from docopt import docopt if _ _ name__ = =' _ _ main__': arguments = docopt (_ _ doc__) Version='0.1.1rc') print (arguments) is here to share the correct posture of Python developers for document-oriented programming. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 246
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.