10 个 推荐的 Python 代码习惯
日常工作需要写很多脚本和小项目,分享一些经验和代码习惯,比较主观,有爱自取,求同存异。
使用 tqdm 包查看处理进度,复杂情况可以考虑 fastprogress
参数过多,并且希望终端直接修改,推荐 YACS — Yet Another Configuration System
如果可配置参数比较多,使用容易错误,可以增加确认的过程
enter = raw_input("confirm (y/n): ") if enter.lower() != 'y': exit()
无需前端知识,可以使用开源库 streamlit 快速构建机器学习相关的 web debug 工具 Streamlit — The fastest way to build custom ML tools
import streamlit as st st.write('Hello, world!')
如有可能,尽量格式化排版
小脚本对文件的处理可以通过 print 方式直接输出,方便使用管道命令进一步处理
运行报错时,直接对那段代码加一个异常捕捉 + IPDB 调试,简单高效
try: do_something_with_xxxError() except xxxError: import ipdb; ipdb.set_trace()
不要重复造轮子,也要注意把自己常用的代码片段收集整理
def split_chunks(data, n): if data is None: return None N = len(data) m = int(math.ceil(N / float(n))) res = [[] for i in range(n)] for i in range(n): res[i] = data[i*m: (i+1)*m] return res
多使用列表表达式,简化常用代码。
with open(path) as f: lines = [l.strip() for l in f.readlines()]
可以允许单文件脚本较长,但不允许单函数又臭又长,理清逻辑,划分为多个函数方便修改。
本作品采用《CC 协议》,转载必须注明作者和本文链接
可以发一篇详细介绍列表表达式的文章吗 :horse: :horse: