Python function returns:

Duncan Booth duncan.booth at invalid.invalid
Thu May 4 08:38:09 EDT 2006


Michael Yanowitz wrote:

>   In Python, there does not seem to be an easy way to have functions
>   return 
> multiple values except it can return a list such as:
> strHostname, nPortNumber, status = get_network_info (strIpAddress,
> strHostname,
>                                                      nPortNumber)
>   Am I missing something obvious? Is there a better, or more standard
>   way 
> to return values from functions?

The only obvious thing you are missing is that you don't pass in values 
which are only results. Duplicating the parameters and results as you have 
above would be unlikely to happen very much in practice.

Oh, and it doesn't return a list, it actually returns a tuple but it is 
easiest just to think of your function as just returning three results.

Returning additional results is better than rebinding parameters because it 
makes it really clear at the point of calling which variables are 
parameters and which are results.

The other not very pythonic thing about your example is that it returns a 
status code: Python largely tends towards using exceptions rather than 
status codes, so if in C you had:

 switch ((status=get_network_info(addr, &host, &port)) {
 case S_OK:
    break;
 case ERROR_1:
    ... handle error ...
    break;
 case default:
    ... handle other errors ...
 };

In Python you would have something like:

   try:
      host, port = get_network_info(addr)
   except ERROR_1:
      ... handle error ...
   except:
      ... handle other errors ...

which means you can handle the error either right next to the call or at 
some outer level (you don't have to manually propogate your status), you 
can't accidentally forget to check the status code, and the actual call is 
much simpler and clearer (especially if the error is handled at some outer 
level).



More information about the Python-list mailing list