stylistic question -- optional return value

Andrew Koenig ark at research.att.com
Thu Aug 29 00:09:01 CEST 2002


doug> On Wed, 28 August 2002, Andrew Koenig wrote:
>> 
>> Suppose I have a function that sometimes returns one value and sometimes
>> returns two.  What's the cleanest way to define such an interface?
>> 
>> For the sake of this discussion, I'll use x to refer to the value that
>> is always returned and y to refer to the optional value.

doug> How about this:

doug> class Result:
doug>     pass

doug> def the_function:
doug>     result = Result();
doug>     result.x = 42
doug>     if some-condition:
doug>         result.y = "aha!"
doug>     return result


On my machine, the following program takes 32.7 seconds:

    class Result:
        pass

    def the_function(cond):
        result = Result();
        result.x = 42
        if cond:
            result.y = "aha!"
        return result

    for i in range(1000000):
        the_function(i % 2)

whereas this version takes 11.3 seconds:

    def the_function(cond):
        x = 42
        y = None
        if cond:
            y = "aha!"
        return (x, y)

    for i in range(1000000):
        the_function(i % 2)

and this one takes 17.7:

    def the_function(cond):
        result = {'x': 42}
        if cond:
            result['y'] = "aha!"
        return result

    for i in range(1000000):
        the_function(i % 2)
    




More information about the Python-list mailing list