Returning different types based on input parameters

Aahz aahz at
Thu Apr 9 20:10:46 CEST 2009

In article <aae921d1-4c8b-4758-a2ab-e4681952ddc2 at>,
George Sakkis  <george.sakkis at> wrote:
>To take it further, what if f wants to return different types,
>differing even in a duck-type sense? That's easier to illustrate in a
>API-extension scenario. Say that there is an existing function `solve
>(x)` that returns `Result` instances.  Later someone wants to extend f
>by allowing an extra optional parameter `foo`, making the signature
>`solve(x, foo=None)`. As long as the return value remains backward
>compatible, everything's fine. However, what if in the extended case,
>solve() has to return some *additional* information apart from
>`Result`, say the confidence that the result is correct ? In short,
>the extended API would be:
>    def solve(x, foo=None):
>        '''
>        @rtype: `Result` if foo is None; (`Result`, confidence)
>        '''
>Strictly speaking, the extension is backwards compatible; previous
>code that used `solve(x)` will still get back `Result`s. The problem
>is that in new code you can't tell what `solve(x,y)` returns unless
>you know something about `y`. My question is, is this totally
>unacceptable and should better be replaced by a new function `solve2
>(x, foo=None)` that always returns (`Result`, confidence) tuples, or
>it might be a justifiable cost ? Any other API extension approaches
>that are applicable to such situations ?

For this particular trick, I would always use a unique sentinel value so
that *only* passing an argument would change the result signature:

    sentinel = object()
    def solve(x, foo=sentinel):
        @rtype: `Result` if foo is sentinel; (`Result`, confidence) otherwise.

But I agree with other respondents that this is a code stink.
Aahz (aahz at           <*>

Why is this newsgroup different from all other newsgroups?

More information about the Python-list mailing list