您如何知道变量是否已在运行时在代码中的特定位置设置?这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除.我正在寻找像defined()Perl isset(),PHP或defined?Ruby中的东西.
if condition:
a = 42
# is "a" defined here?
if other_condition:
del a
# is "a" defined here?
Run Code Online (Sandbox Code Playgroud) 在测试变量有值时,是否有理由决定使用哪一个try或哪些if结构?
例如,有一个函数返回列表或不返回值.我想在处理之前检查结果.以下哪一项更可取,为什么?
result = function();
if (result):
for r in result:
#process items
Run Code Online (Sandbox Code Playgroud)
要么
result = function();
try:
for r in result:
#process items
except TypeError:
pass;
Run Code Online (Sandbox Code Playgroud)
我认为可以接受的是,作为Java中的一般规则(也许是任何具有异常处理的语言),应该尽量避免使用异常处理来实际处理业务逻辑.一般来说,如果预计会发生某种情况,那么应该检查它并直接处理它,而不是依赖于异常处理来为您进行检查.例如,以下不被视为良好做法:
try{
_map.put(myKey, myValue);
} catch(NullPointerException e){
_map = new HashMap<String, String>();
}
Run Code Online (Sandbox Code Playgroud)
相反,懒惰初始化应该更像这样:
if(_map == null){
_map = new HashMap<String, String>();
}
_map.put(myKey, myValue);
Run Code Online (Sandbox Code Playgroud)
当然,可能存在比简单处理延迟初始化更复杂的逻辑.因此,鉴于此类事情通常不受欢迎......如果有的话,依靠发生某种业务逻辑的异常是一个好主意吗?是否准确地说任何一个人感到被迫使用这种方法的实例是否真的突出了所使用的API的弱点?
什么时候异常处理比条件检查更可取?在很多情况下我可以选择使用其中一种.
例如,这是一个使用自定义异常的求和函数:
# module mylibrary
class WrongSummand(Exception):
pass
def sum_(a, b):
""" returns the sum of two summands of the same type """
if type(a) != type(b):
raise WrongSummand("given arguments are not of the same type")
return a + b
# module application using mylibrary
from mylibrary import sum_, WrongSummand
try:
print sum_("A", 5)
except WrongSummand:
print "wrong arguments"
Run Code Online (Sandbox Code Playgroud)
这是相同的功能,避免使用异常
# module mylibrary
def sum_(a, b):
""" returns the sum of two summands if they are both of the same …Run Code Online (Sandbox Code Playgroud) 我有一个User对象和一个UserInfo具有一对一关系的对象.我只是添加UserInfo对象,所以一些用户已经有User对象,但没有UserInfo对象.我想检查User对象是否有与之关联的UserInfo对象,如果没有将它们重定向到我可以获取一些信息的页面.我仍然是python的新手,并尝试做一个if request.user.user_info:在它不存在时抛出异常所以我最终这样做:
user = request.user
try:
user.user_info.university
except:
print 'redirect to info page'
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,但我觉得异常应该是异常,而不是if语句替换.有一个更好的方法吗?
我继承了一个代码库,其中包含如下代码(注意:示例代码是PHP):
try {
// Do something which doesn't intentionally throw exceptions.
} catch (\Exception $e) {
$this->log->log($e->getMessage());
$this->product->setError($e->getMessage());
return false;
}
Run Code Online (Sandbox Code Playgroud)
基本上,代码正在捕获异常.记录它,以及静默失败(除了日志消息).
这种行为似乎在生产中有意义,但使开发变得更加困难(因为必须在日志文件中查找堆栈跟踪,而不是将其打印到控制台).所以我想出了以下功能:
private function tryCatch ($func) {
// Bind closure, so that $this allows it to access class properties
if (is_object($func) && ($func instanceof Closure)) {
\Closure::bind($func, $this, "static");
}
if (\App::environment('test')) {
return $func();
} else {
try {
return $func();
} catch (\Exception $e) {
$this->log->log($e->getMessage());
$this->product->setError($e->getMessage());
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样使用:
$this->tryCatch(function () {
// …Run Code Online (Sandbox Code Playgroud) 我有一个特别的问题,让我难过.假设我有以下两个列表:
x = ["A","B","C","D","E"]
y = [1,2,3,2,1]
Run Code Online (Sandbox Code Playgroud)
x并y有一段感情.这种关系与指数挂钩.也就是说,"A"涉及1,"B"涉及2,"C"涉及3,依此类推.
我要做的是创建一个键值关系,其中唯一项y是键,每个键都有一个列表,其中包含与前面提到的键相关的字母.我试图做以下事情:
mapping = dict(zip(y,x))
{1: 'E', 2: 'D', 3: 'C'}
Run Code Online (Sandbox Code Playgroud)
这会覆盖上一封信.我希望能够返回以下内容:
{1:['A','E'], 2:['B','D'], 3:['C']}
Run Code Online (Sandbox Code Playgroud)
任何人都有这个聪明的解决方案?最好没有itertools.