侧边栏壁纸
博主头像
Zeeland

全栈算法工程师 | 大模型创业 | 开源项目分享 | Python开发者 | @Promptulate Founder | @SparkLab cofounder | @LangChainAI Top Contributor | @CogitLab core member

  • 累计撰写 61 篇文章
  • 累计创建 47 个标签
  • 累计收到 7 条评论

目 录CONTENT

文章目录

Python开发规范记录

Zeeland
2022-12-15 / 0 评论 / 0 点赞 / 278 阅读 / 840 字

Introduction

最近python用的多,在参考了一些比较标准的开发规范后,如google styleguide,总结了一些下来,当然更多的内容,还是直接看相关的文档就好,文章结尾附上了笔者参考的文档链接,直接阅读最佳。

Some rules

Main

即使是一个打算被用作脚本的文件, 也应该是可导入的. 并且简单的导入不应该导致这个脚本的主功能(main functionality)被执行, 这是一种副作用. 主功能应该放在一个main()函数中.

在Python中, pydoc以及单元测试要求模块必须是可导入的.
你的代码应该在执行主程序前总是检查 if __name__ == '__main__'
这样当模块被导入时主程序就不会被执行.

def main():
     print('run')

if __name__ == '__main__':
    main()

默认迭代器和操作符

优点:

  • 默认操作符和迭代器简单高效, 它们直接表达了操作, 没有额外的方法调用.
  • 使用默认操作符的函数是通用的. 它可以用于支持该操作的任何类型.

缺点:

  • 你没法通过阅读方法名来区分对象的类型(例如, has_key()意味着字典). 不过这也是优点.
# 内建类型也定义了迭代器方法. 优先考虑这些方法, 而不是那些返回列表的方法.
# 当然,这样遍历容器时,你将不能修改容器.

# Yes:  
for key in adict: ...
if key not in adict: ...
if obj in alist: ...
for line in afile: ...
for k, v in dict.iteritems(): ...

# No:
for key in adict.keys(): ...
if not adict.has_key(key): ...
for line in afile.readlines(): ...

作者:后厂程序员
链接:https://zhuanlan.zhihu.com/p/161895742
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

True/False的求值

# 1. 永远不要用==或者!=来比较单件, 比如None. 使用is或者is not.

# 2. 注意: 当你写下 `if x:` 时, 你其实表示的是 `if x is not None` .

# 3. 永远不要用==将一个布尔量与false相比较. 使用 `if not x:` 代替.
#    如果你需要区分false和None, 你应该用像 `if not x and x is not None:` 这样的语句.

# 4. 对于序列(字符串, 列表, 元组), 要注意空序列是false.
#    因此 `if not seq:` 或者 `if seq:` 比 `if len(seq):` 或 `if not len(seq):` 要更好.

# 5. 处理整数时, 使用隐式false可能会得不偿失(即不小心将None当做0来处理).
#    你可以将一个已知是整型(且不是len()的返回结果)的值与0比较.

# Yes:
     if not users:
         print 'no users'

     if foo == 0:
         self.handle_zero()

     if i % 10 == 0:
         self.handle_multiple_of_ten()
        
#No:  
     if len(users) == 0:
         print 'no users'

     if foo is not None and not foo:
         self.handle_zero()

     if not i % 10:
         self.handle_multiple_of_ten()
        
# 注意‘0’(字符串)会被当做true.

最后,在阅读过google styleguide之后,笔者在pycasbin顺带修改了一个style的问题并pr了一下,参考https://github.com/casbin/pycasbin/pull/282

References

0

评论区