Newbie question: Returning mutable vs. immutable

John Roth newsgroups at jhrothjr.com
Thu Apr 15 10:57:51 EDT 2004


<pugnatio2 at yahoo.com> wrote in message
news:997a06e0.0404150627.5fb95d9b at posting.google.com...
> Hi, Does anyone have an opinion as to whether functions/methods should
> return mutable or immutable objects? In some circumstances, I could
> see that mutable objects might be more convenient, but if the function
> is to be reused, it might be a good idea to return only immutables.
>
> Or is this question moot, since the function returns control to the
> caller and is out of the picture at that point?
>
> Thanks,
>
> --p

I'm not sure I understand the question. The entire reason (well, not
the *entire* reason, but close enough on the novice level) you write
functions is to use them again and again and again. So your function
should return whatever it needs to.

In thinking about this, it seems there is really only one place where
you would have a choice of mutable or immutable: a list or a tuple.
Think of a tuple as a packaging method for a number of distinct
values that you want to return. For example, if I say:

return spam, eggs, juice

the compiler builds a tuple. If I wanted to return a list, I'd have
to say:

return [spam, eggs, juice]

John Roth





More information about the Python-list mailing list