writing idiomatic python 读书笔记(7)

格式化
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 来引用命令行参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值