dangelsaurus
dangelsaurus

Reputation: 7562

Python, Do I need to return an object that was passed in as parameter?

When writing a function which accepts a mutable object, which will could be changed, is it necessary to return this object to the caller?

By necessary I mean...

  1. Is there a specific PEP guideline around this?
  2. If not, what is most common in the world of Python programming?

A little bit of code:

def foo(args):
    args['a'] = 'new-value'
    args['b'] = args['b'] + 1

    # is there a need for a 'return args' ?

args = {'a': 'old-value', 'b': 99}
foo(args) # is there a need for args = foo(args)
print(args['a'], args['b']) # outputs new-value 100

"Explicit is better than implicit." makes me think I should make the potential for args to change very explicit in the main body, so that one does not have to look into the function to see if args might be changed...

Upvotes: 1

Views: 468

Answers (2)

Kind Stranger
Kind Stranger

Reputation: 1761

In terms of what is more commonplace in python, there are some examples where the object passed is altered. These tend to be methods of the object to be amended (e.g. list.append, where list is a type), but most functions tend to take a copy of the object passed and return a new one (e.g. string.strip, where string is the module string).

This of course also brings up str.strip which is also a method of a str type object which returns a new object.

Upvotes: 0

coderanger
coderanger

Reputation: 54247

This is not covered by any PEP, and it's really up to style of the author. Generally in API design though, methods that mutate arguments won't return anything so you don't forget you're mutating things. Be very careful with this kind of design.

Upvotes: 2

Related Questions