views:

210

answers:

5

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 (from 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.

+11  A: 

Could you use exceptions to indicate failure, rather than return codes? Then most of your if result != OK: statements would simply go away.

RichieHindle
I agree. Return codes are not very "pythonic", or considered good practice in any modern language I can think of.
Mike
I wanted to save exceptions for 'exceptional' cases. These functions may be expected to return these codes. I always thought it was bad practice to count on exceptions for anything other than catching exceptional scenarios.
cgyDeveloper
Won't that just create a series of try/except blocks, then? Or is there some elegant handling syntax I don't know of.
cgyDeveloper
You don't need a *series* of `try`/`except` blocks, no. You can say `try: this() that() and() the() other() except...`
RichieHindle
@cgyDeveloper: Not really, you should program for one scenario. If the flow goes away from that scenario, and you do have alternative scenarios, then you could code them and use polymorphism to handle them. Not necessarily filling all the code with `if code = 2: this, if code = 4: that' or `try:this() try that()` but instead have `object = Factory.getHandlerFor( conditions )` have that object to fulfill the particula condition. :-/ It's hard to explain in a comment.
OscarRyz
+3  A: 

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!

SilentGhost
Maybe there is no nice syntax for this. I wanted to see what those who are more familiar with the language would come up with.
cgyDeveloper
for this you need to provide some real code
SilentGhost
+1  A: 

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.

Andrey Vlasovskikh
A: 

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?

Triptych
+2  A: 

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()
dbr
Right, when I discovered that the first statement you wrote isn't possible I came here for suggestions. I guess it's just not there. I'll review my codes/exceptions logic, though, based on so many suggestions.
cgyDeveloper