Testing a module's return

Fredrik Lundh effbot at telia.com
Thu Apr 20 04:40:59 EDT 2000


Joal Heagney <sctheagn at kraken.itc.gu.edu.au> wrote:
> I've found that I have to define several of my modules such that they
> return a string if they fail, rather than 0. (Let's face it, there are a
> lot more things that can go wrong than right). Now I originally wanted
> to have these modules return the values I was after. eg.
>
> def function_name(arg1, arg2, arg3, .... argN):
>     do something with the args, return value
>
> But as a beginner, *grins* I've found returning error strings a little
> more important
>
> def function_name(arg1, arg2, arg3, .... argN):
>     check for error condition 1:
>         return 'Whoops'
>     check for error condition 2:
>         return 'What are you doing, Dave?'
>     check for error condition 3:
>         return 'That ain't right, or humanly decent either'
>     do something with the args, return something.
>
> I can't sort out, should I return 0 for a success, and give the answer
> as a set attribute (Eg. a class variable)? Or is there a much neater way
> of doing things? There'd have to be.

if you had read the tutorial, you'd seen the answer: exceptions!

    def function_name(arg1, arg2, arg3, .... argN):
        assert not error condition 1, "Whoops!"
        assert not error condition 2, 'What are you doing, Dave?'
        ...
        do something with the args
        return something

for details, see chapter 8 in the tutorial:
http://www.python.org/doc/current/tut/node10.html

more info on the "assert" statement is found here:
http://www.python.org/doc/current/ref/assert.html

</F>





More information about the Python-list mailing list