Skip to main content

Python: Returning Multiple Things of Different Types

If you are a strong believer in statically typed languages, you won't want to read this post!

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 the
following as appropriate:

successful
This is a bool to indicate success.

pylons_response
If unsuccessful, this is a Pylons response object that your
controller can return. It will contain an appropriate error
message for the user.

file_handle
Upon success, this is the file handle returned by
``urllib2.urlopen``. Per urllib2, it has an ``info()`` method
containing things like headers, etc.

xml_document
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.
The calling code then looks like this:
        server_response = talk_to_server(parse_xml_document=True)
if not server_response['successful']:
return server_response['pylons_response']
etag = server_response['file_handle'].info().getheader('ETag')
xml_document = server_response['xml_document']
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.

Comments

Anonymous said…
I've seen this in a few places, but with the slight change that the return is a new type, and the keys are attributes. The benefits are:

1. slightly shorter syntax to access to the results:
server_response = talk(p)
xml_document = server_response.xml_document
# except if you give server_response a short name, then you might not even bother reassigning the xml_document value to its own variable name

2. clearer output when people print or inspect the result:
>>> print talk(p)
<server_response with some interesting summary of the pieces of the result>
>>> help(talk(p).xml_document) # might work if you use properties


Also, your (False, reason) example doesn't look very pythonic to me. I can't think of why you wouldn't use an exception, which itself might be annotated with some other attributes.
John Speno said…
I like it.
EY said…
And in Python 2.6, you'll also be able to use named tuples via collections.NamedTuple.
Anonymous said…
Why do you say strongly typed advocates should not ready your post?
I return proper values or error values all the time. In a completely strongly typed a and checked manner. And with simpler syntax. Just pick your language.
(Mine is Haskell.)
Simon Wittber said…
Actually, the text reads:

If you are a strong believer in statically typed languages, you won't want to read this post!

Strong != Static
Anonymous said…
What anonymous above is referring to is Haskell's Maybe datatype. See also the Either datatype just below that.

James Graves
jjinux said…
I know about Maybe and Either. Thanks for the reminder, though.

When I said "If you are a strong believer in statically typed languages, you won't want to read this post!" I was referring to the fact that many Java programmers might get upset about the fact that I was using a dict in order to get around having to declare exactly what I was going to return.

Naturally, Maybe in Haskell is strongly typed, so it's a different ball of wax. Furthermore, in Haskell, it's quite natural to return a big list of stuff and do pattern matching on the return value.

Popular posts from this blog

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from