Alternative to returning dictionaries instead of tuples from user-defined functions

Viewed 115

I frequently find myself returning dictionaries instead of tuples when defining functions in Python with many outputs (say 5-20). For example, I may define a function with many outputs:

def my_fun_conventional(a,b,c):
    sum_ = a+b+c
    prod_ = a*b*c
    return a, b, c, sum_, prod_

I like to return a dictionary instead, which lets me access the output differently.

def my_fun_dict(a,b,c):
    sum_ = a+b+c
    prod_ = a*b*c

    return {'a': a, 'b': b, 'c': c, 'sum': sum_, 'prod': prod_}

    output = my_fun_dict(1,2,3)
    output['sum']

I often prefer the second function for two reasons: (1) I don't have to worry about conflicting names in globals and (2) I don't have to worry about making sure that the order of returned objects and assigned names line up perfectly; if I change the order I specify key-value pairs in the dictionary, it doesn't matter. The latter reason is particularly relevant for rapid development when I am constantly changing the output of the functions, and since I am an NLP researcher, I am mostly in development.

However, I don't see other people returning dictionaries. This leads me to believe I am doing something inadvisable. So my first question is: Is there something inadvisable about returning dictionaries as I do? If so, is there a nice way to achieve the two goals discussed above?

If what I do is not inadvisable, I have a follow-up question: It is annoying to have to type each variable name twice in the dictionary (once for the key, once for the value)—is there some way to do this in a nicer way? I'm envisioning some sort of utility function (say output_dict) that would do this

def my_fun_dict(a,b,c):
    sum_ = a+b+c
    prod_ = a*b*c

    return output_dict(a, b, c, sum_, prod_)

Again, it feels like there might be a pythonic alternative since I can't be the first person to deal with this issue.

0 Answers
Related