2

I have a function that modifies 2 mutable objects (a list and a dict).
Given the nature of python If I modify them inside the function then the changes are supposed to be visible from outside.

My question is what convention/best practise says about returning values?

my_dict = {
    'flag' : False
}

my_list = [
    {'color': 'blue'}, 
    {'color': 'yellow'}
]

def modify_in_place(my_dict_param, my_list_param):
    my_dict_param['flag'] = True
    for item in my_list_param:
        item['color'] = 'red'

    # nothing in this case
    return

modify_in_place(my_dict, my_list)
# Now both arguments should reflect their modified states 

Is the above code considered the best way to do this, or would this be "better"?

def modify_in_place(my_dict_param, my_list_param):
    my_dict_param['flag'] = True
    for item in my_list_param:
        item['color'] = 'red'

    return my_dict_param, my_list_param

my_dict, my_list = modify_in_place(my_dict, my_list)

In this case I'm returning the input (modified) values that will overwrite the original name references.

The result is supposed to be the same in both cases.

I'm aware that "better than" questions might be biased by opinions but given that python has often conventional ways to do things I'm asking about the "python way"

Leonardo
  • 4,046
  • 5
  • 44
  • 85
  • To me the second more is better, but the only thing relevant thing I have to back that up is from The Zen of Python "Explicit is better than implicit.", but an argument could probably be made that both are explicit. But you're right, they're both almost functionally the same, I think the second one just has an extra assignment operation. – Hoopdady Mar 15 '17 at 15:25
  • 1
    @Hoopdady: which is why the Python API explicitly returns `None`, to signal that the objects have been altered in-place. – Martijn Pieters Mar 15 '17 at 15:26
  • 1
    Relevant: http://stackoverflow.com/a/1682601/6260170 – Chris_Rands Mar 15 '17 at 15:29

1 Answers1

2

The convention in Python is that if a function operates in-place, it returns None. You can see this for example in the list methods .sort and .append, which modify the lists they are called on but return None.

Note, your first example does not need return at all.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895