python语言-It's better to ask forgiveness than permission

python编程中,对于这句话的理解。本质是两种不同的变成风格。当然,我知识看到了这个问题,查了查相关的解释。我本省对这个问题并没有很好的认识。所以,下文内容主要来自于stackoverflow的一段解释的搬运。我先附上[原帖的链接]

问题描述

Ask forgiveness, not permission” opposes two programming styles!

  • “Ask for permission” goes like this
if can_do_operation():
    perform_operation()
else:
    handle_error_case()
  • “Ask forgiveness” goes like this:
try:
    perform_operation()
except Unable_to_perform:
    handle_error_case()

下面附上作者给的解释:
There are two main reasons why it’s better to ask for forgiveness:

In a concurrrent world (in a multithreaded program, or if the operation involves objects that are external to the program such as files, other processes, network resources, etc.), the situation might change between the time when you run can_do_operation() and the time when you run perform_operation(). So you’d have to handle the error anyway.

You need to use exactly the right criteria for asking permission. If you get it wrong, you’ll either be unable to perform an operation that you could perform, or have an error occur because you can’t perform the operation after all. For example, if you test whether a file exists before opening it, it’s possible that the file does exist, but you can’t open it because you don’t have permission. Conversely, maybe the file is created when you open it (for example because it comes over a network connection that is only brought up when you actually open the file, not when you only poke to see whether it’s there).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值