Sometimes it makes sense for a function to return multiple things. In such cases, it's common to just return them in a tuple: "return (count, new_obj)".
Sometimes you might want to return objects of different types based on whether an operation succeeded or not. For instance, if the operation was successful, you might return "(True, obj)". If it failed, you might return "(False, reason)". Often, you can use exceptions to handle this situation.
Sometimes you might want to return objects of different types based on arguments to the function. For instance, did the caller ask for the data in this format or that format?
Sometimes you'll want all of these variations at the same time. In such cases, I have found that using a dict for your return value is a good solution. For instance, here is a piece of a docstring that I wrote yesterday:
Return a dict (which I often call "response") with one or more of theThe calling code then looks like this:
following as appropriate:
This is a bool to indicate success.
If unsuccessful, this is a Pylons response object that your
controller can return. It will contain an appropriate error
message for the user.
Upon success, this is the file handle returned by
``urllib2.urlopen``. Per urllib2, it has an ``info()`` method
containing things like headers, etc.
Upon success, if you set ``parse_xml_document=True``, this will
contain the parsed xml_document. I'll take care of parsing errors
with an appropriate pylons_response for you.
server_response = talk_to_server(parse_xml_document=True)If you read it out loud, the code "reads" easily, and yet it has the flexibility to contain all the different things I need to return. If I ask for something that isn't there, I get an exception, which is life as usual for a Python programmer.
if not server_response['successful']:
etag = server_response['file_handle'].info().getheader('ETag')
xml_document = server_response['xml_document']