Home > Software design >  Is it possible to have different return in the same function?
Is it possible to have different return in the same function?

Time:10-04

I have that function :

def choice(default=True):
    if default:    
        return 1
    else:
        return 0, "Your choice is 0"

In the first case I get one variable, in the second case I get two variables.

Is it a problem to do that in Python ? I tested and it works, but for instance in c that kind of things does not work. Do you know if there is a rule about that such as PEP8 or something like that ?

Thank you very much !

CodePudding user response:

In the first case I get one variable, in the second case I get two variables.

Actually in both cases you get a single object. In the first case it is an int, and in the second case it is a tuple (with int and string inside).

Is it a problem to do that in Python ?

Technically? No. In terms of maintenance and readability? Yes. Can you imagine someone's surprise when he realizes that changing an argument changes the type of the result (in your case int vs tuple)? What's worse these types are completely unrelated. Typically noone will expect that. And then they have to write weird logic to handle it. Annoying.

Also how would you document this function? The return type is inconsistent, unless you simply say "it returns an object" which is too general to be useful.

Finally such design will likely confuse any static code analysis. And we want static analysis to reduce human errors.

I tested and it works, but for instance in c that kind of things does not work.

It does work in C as well (and probably in any language), although in a bit different way. After all what Python returns is "an object", it is up to the caller to interpret that. It is very similar to return void* from a C function and force the caller to do appropriate cast. Which is a very bad practice as well. Even worse, since C is strongly typed.

Do you know if there is a rule about that such as PEP8 or something like that ?

Well, not explicitly about this situation, but "PEP 8 -- Style Guide for Python Code" does say "Be consistent in return statements.".

CodePudding user response:

It's absolutely fine to have a function with different return value signatures, depending on the options passed. See np.unique for example. Since Python does not have function overloading, this is the canonical way of achieving that. The important point is to document it properly. In the example of np.unique you'd otherwise have to define eight different versions of the function with all combinations of return values. Impractical, hard to maintain, and mostly redundant.

Another way to handle this kind of "function overloading" in Python is to always use the same return value signature, but return None for unused values. I like the former method better.

  • Related