richardmyu / blog

个人(issues)博客
https://github.com/richardmyu/blog/issues
MIT License
0 stars 0 forks source link

python 语法异常(基于 PEP8)汇总 #25

Open richardmyu opened 3 years ago

richardmyu commented 3 years ago

1.Rmove redundant parentheses

删除多余的小括号。多见于 if 条件判断时。

if (not os.path.exists(path + "/tmp")):

if not os.path.exists(path + "/tmp"):

至于为什么不推荐带上小括号,个人猜测跟元组有关系。

在 Inspections 中,对应的条目为 Redundant parentheses,其对应的 Options 为:

2.Too broad exception clause

捕获的异常过于宽泛,没有针对性。多见于 try...except...

# 捕获所有异常
try:
    # do something
except:
   # do something

# 捕获指定异常
try:
    # do something
expect <异常名>:
    # do something

解决方法:指定精确的异常类型。详见 BaseException

如果不知道异常的类型呢?没关系,还有一个兜底的 :clap::clap::clap::

# 然鹅 Exception 也会报出同样提示的波浪线,这,写了个寂寞
try:
    # do something
except Exception:
    # do something

Inspection info: This inspection highlights too broad exception clauses such as no exception class specified, or specified as 'Exception'.