糟糕的Python编程习惯


#糟糕的代码风格
try:
    do_something()
except:
    pass

#值得提倡的代码风格
try:
    do_something()
except ValueError:  # Catch some very specific exception - KeyError, ValueError, etc.
    pass
#会引发Exception的函数样例
def get_number():
    return int('foo')
#利用logging模块 [最佳实践__使用默认Python库已经提供的方法而不是自己去写]
import logging
try:
    x = get_number()
except Exception as ex:
    logging.exception('Caught an error')
# The Python 2.x version. It's a little less work.
import sys
import traceback
def log_traceback(ex, ex_traceback):
    tb_lines = traceback.format_exception(ex.__class__, ex, ex_traceback)
    tb_text = ''.join(tb_lines)
    # I'll let you implement the ExceptionLogger class, and the timestamping.
    exception_logger.log(tb_text)
try:
    x = get_number()
except Exception as ex:
    # Here, I don't really care about the first two values.
    # I just want the traceback.
    _, _, ex_traceback = sys.exc_info()
    log_traceback(ex, ex_traceback)
# The Python 3 version. It's a little less work.
import traceback
def log_traceback(ex):
    tb_lines = traceback.format_exception(ex.__class__, ex, ex.__traceback__)
    tb_text = ''.join(tb_lines)
    # I'll let you implement the ExceptionLogger class, and the timestamping.
    exception_logger.log(tb_text)
try:
    x = get_number()
except Exception as ex:
    log_traceback(ex)
import sys
import traceback
def handle_exeception(e):
    traceback.print_exc()
    try:
        raise Exception
    except:
        f = sys.exc_info()[2].tb_frame.f_back
    print 'EXCEPTION|%s:%s:%d "%s"' %(f.f_code.co_filename, f.f_code.co_name, f.f_lineno, e)
    return

try:
    x = get_number()
except Exception, e:
    handle_exeception(e)

 

英文链接:

https://realpython.com/blog/python/the-most-diabolical-python-antipattern/

相关链接:

《“糟糕的Python编程习惯”》 有 5 条评论

  1. Python Tips – 防御性编程风格 EAFP vs LBYL
    https://mp.weixin.qq.com/s/r8pUVe67SwaCfZq4PAsjFg
    `
    “Easier to Ask for Forgiveness than Permission.”(请求宽恕比许可更容易)— EAFP

    “Look Before You Leap”(三思而后行 )— LBYL

    如果有潜在不可控的问题,使用 EAFP ;
    如果预先检查成本很高,请使用 EAFP ;
    如果您希望操作在大多数时间成功,请使用 EAFP ;

    如果您预计操作失败的时间超过一半,请使用 LBYL ;

    如果速度不重要,使用您认为更易读的风格;
    `

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注