格式化
1.全局变量大写
2.根据PEP8格式化代码
在编译器上安装好PEP8style-checking插件
Identifier Type Format Example
Class
Camel case class StringManipulator():
Variable
Words joined by _ joined_by_underscore = True
Function Words joined by _ def multi_word_name(words):
Constant All uppercase SECRET_KEY = 42
3.不要把多个语句放在一行
导入
1.导入顺序
标准模块
第三方模块
本地模块
使用绝对导入,避免相对导入
Harmful:
from ...package import other_module
Idiomatic:
import package.other_module
import package.other_module as other
不要使用import *
from foo import * #避免使用
from foo import (bar, baz, qux,
quux, quuux) #不用括号也可以,当list很长时用tuple可以方便随时换行
# or even better...
import foo
使用try来判断一个包是否可用
try:
import cProfile as profiler
except:
import profile as profiler
print(profiler.__all__)
模块和包
使用__init__.py文件来简化包的导入
# __init__.py:
from gizmo.client.interface import Gizmo
from gizmo.client.contrib.utils import GizmoHelper
#client code:
from gizmo import Gizmo, GizmoHelper
可执行脚本
1.使用 if __name__ == '__main__' 允许文件直接导入和运行
import sys
import os
def divide(a, b):
return a / b
# Will only run if script is executed directly,
# not when the file is imported as a module
if __name__ == '__main__':
first_number = float(sys.argv[1])
second_number = float(sys.argv[2])
if second_number != 0:
print(divide(first_number, second_number))
2.使python脚本直接执行
chmod +x xx.py
3.使用 sys.exit 返回错误代码
通过使用unit管道,来监视代码的运行,减少不必要的程序
def main():
import sys
if len(sys.argv) < 2:
# Calling sys.exit with a string automatically
# prints the string to stderr and exits with
# a value of '1' (error)
sys.exit('You forgot to pass an argument')
argument = sys.argv[1]
result = do_stuff(argument)
if not result:
sys.exit(1)
do_stuff_with_result(result)
return 0
if __name__ == '__main__': sys.exit(main())
4.使用sys.argv 来引用命令行参数