Coursera 笔记

Module 01 · Python Coding Practices and Packaging Concepts

Module 1 Cheatsheet: Python Coding Practices and Packaging Concepts模块 1 速查表:Python 编程实践和打包概念

Coursera ↗

Estimated time needed: 5 minutes
预计所需时间:5 分钟

Package/Method  包/方法 Description  描述 Code Example  代码示例
Packaging  打包 To create a package, the folder structure is as follows:
创建包的文件夹结构如下:

• Project folder → Package name → __init__.py, module_1.py, module_2.py, and so on.
Project 文件夹 → 包名 → __init__.py、module_1.py、module_2.py,等等。

• In the __init__.py file, add code to reference the modules in the package.
在 __init__.py 文件中,添加代码以引用包中的模块。
module1.py

def function_1(arg):
    return <operation output>
__init__.py:

from . import function_1  从 . 导入 function_1
Python Style Guide  Python 风格指南 • Four spaces for indentation
缩进使用四个空格

• Use blank lines to separate functions and classes
使用空行分隔函数和类

• Use spaces around operators and after commas
在运算符周围和逗号后使用空格

• Add larger blocks of code inside functions
在函数内部添加较大的代码块

• Name functions and files using lowercase with underscores
使用小写字母和下划线命名函数和文件

• Name classes using CamelCase
使用驼峰命名法命名类

• Name constants in capital letters with underscores separating words
以大写字母命名常量,用下划线分隔单词
def function_1(a, b):
     if a > b:
如果 a > b:
         c = c + 5
    else:
        c = c - 3
    return c   返回 c
…
c = function_1(a, b)

Constant Definition example
常量定义示例

MAX_FILE_UPLOAD_SIZE
Static Code Analysis  静态代码分析 Use Static code analysis method to evaluate your code against a predefined style and standard without executing the code.
使用静态代码分析方法,在不执行代码的情况下,评估您的代码是否符合预定义的风格和标准。

For example, use Pylint to perform static code analysis.
例如,使用 Pylint 执行静态代码分析。
Shell code:  Shell code:

pylint code.py
Unit Testing  单元测试 Unit testing is a method to validate if units of code are operating as designed.
单元测试是一种验证代码单元是否按设计运行的方法。

During code development, each unit is tested. The unit is tested in a continuous integration/continuous delivery test server environment.
在代码开发过程中,每个单元都会进行测试。单元在持续集成/持续交付测试服务器环境中进行测试。

You can use different test functions to build unit tests and review the unit test output to determine if the test passed or failed.
您可以使用不同的测试函数来构建单元测试,并查看单元测试输出以确定测试是否通过或失败。
import unittest
from mypackage.mymodule import my_function
从 mypackage.mymodule 导入 my_function
class TestMyFunction(unittest.TestCase):

    def test_my_function(self):
        result = my_function(<args>)
        self.assertEqual(result, <response>)
unittest.main()