Condense this Python statement without destroying readability
I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.
I use return codes to verify that my internal functions return successfully. For example (from internal library functions):
result = some_function(arg1,arg2)
if result != OK: return result
or (f开发者_如何转开发rom main script level):
result = some_function(arg1,arg2)
if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result))
Can I get this down to one line without making it unreadable?
EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.
Could you use exceptions to indicate failure, rather than return codes? Then most of your if result != OK:
statements would simply go away.
It sounds as if you want something like..
if result = some_function(arg1, arg2):
return result
This is very deliberately not possible in Python. It's too common a typo to write if a = b
instead of if a == b
, and allowing this mixes assignment with flow-control. If this is necessary, split it into two lines:
x = some_function()
if x:
print "Function returned True"
A more practical example of this is..
result = re.match("a", "b")
if result:
print result.groups()
(more correctly, you should do if result is not None:
in this case, although the above works)
In your specific case ("to verify that my internal functions return successfully"), it sounds like you should use exceptions. If everything is fine, just return whatever you wish. If something goes badly, raise an exception.
Exceptions in Python aren't like many other languages - for example, they are used internally flow control (such as the StopIteration exception)
I'd consider the following far more Pythonic than using return codes:
#!/usr/bin/env python2.6
def some_function(arg1, arg2):
if arg1 + arg2 > 5:
return "some data for you"
else:
raise ValueError("Could not complete, arg1+arg2 was too small")
Then, you can call the function in a single line:
return some_function(3, 2)
This either returns the value, or raises an exception, which you could handle the exception somewhere sensible:
def main():
try:
result = some_function(3, 5)
except ValueError, errormsg:
print errormsg
sys.exit(1)
else:
print "Everything is perfect, the result was {0}".format(result)
Or if this case is actually an error, simply let halt the application with a nice stack trace.
Yes, it's much longer than one line, but the idea behind Python is brevity, but explicitness and readability.
Basically, if the function can no longer continue, raise an exception. Handle this exception either where you can recover from the problem, or present the user with an error message.. unless you are writing a library, in which case leave the exception to run up the stack to the calling code
Or, in poem form:
$ python -m this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Finally, it might be worth reading over "PEP 8", the style guide for Python. It may answer some of your questions, such as "Are one-liner if statements 'pythonic'?"
Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah': do_blah_thing() do_one() do_two() do_three()
Rather not:
if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three()
pythonic:
An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages.[...]
Does not imply writing on-liners!
If you insist on not using exceptions, then I would write two lines (one line will be too long here):
res = some_function(arg1, arg2)
return res if res != OK else ...
By the way, I recommend you to come up with some static type of values your function returns (despite of dynamic typing in Python). For example, you may return "either int
or None
". You can put such a description into a docstring.
In case you have int
result values and int
error codes you may distinguish them by introducing an error class:
class ErrorCode(int): pass
and then checking if the result isinstance
of ErrorCode
.
In addition to exceptions, using a decorator is a good solution to this problem:
# Create a function that creates a decorator given a value to fail on...
def fail_unless(ok_val):
def _fail_unless(f):
def g(*args, **kwargs):
val = f(*args, **kwargs)
if val != ok_val:
print 'CALLING abort_on_error...'
else:
return val
return g
return _fail_unless
# Now you can use the decorator on any function you'd like to fail
@fail_unless('OK')
def no_negatives(n):
if n < 0:
return 'UH OH!'
else:
return 'OK'
In practice:
>>> no_negatives(9)
'OK'
>>> no_negatives(0)
'OK'
>>> no_negatives(-1)
'CALLING abort_on_error...'
I know the syntax defining fail_unless
is a little tricky if you're not used to decorators and function closures but the application of fail_unless()
is quite nice no?
精彩评论