I have a this code in PHP:
if($id = $this->ci->srr->check_faca_indiv($name))
{
return $id;
} elseif($id = $this->_addIndiv($name)) {
return $id;
} else {
return null;
I use this basic structure all over the place and it may not be great, but it's what I'm used to. The functions basically try to do some simple operations and if they fail they return a null value. I tried to mimic that in porting it over to Python, but got syntax errors and ended up modifying it to this:
indiv_id = checkIndiv(name)
if indiv_id != None:
return indiv_id
indiv_id = addIndiv(name)
if 开发者_开发百科indiv_id != None:
return indiv_id
else:
return None
I think that gets me to the same place but I don't like it as much -- is there a way more similar to PHP that I'm missing?
something like:
return checkIndiv(name) or addIndiv(name)
The basic problem with your code is that the final branch serves no purpose. Even in your PHP example it basically says:
if (null) return null;
You can reduce everything to:
indiv_id = checkIndiv(name)
if indiv_id:
return indiv_id
else:
return addIndiv(name)
(If indiv_id could become something that compares to False
, you should check against None
, but use is
instead of ==
!)
Maybe you could work with exceptions:
def check_or_add(name):
try:
return checkIndiv(name)
except CheckException:
return addIndiv(name)
On the whole, though, your semantics strike me as odd: I would not expect a function with "check" in the name to return an object instead of simply True
or False
. I'd probably use different names:
id = get_indiv(name)
if id:
return id
else:
return new_indiv(name)
That makes James' solution more readable as well:
return get_indiv(name) or new_indiv(name)
精彩评论