Newbie question: Returning mutable vs. immutable

P

pugnatio2

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
 
R

Roy Smith

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 don't think there's any general rule for this. Return what makes
sense to return and don't worry about the mutability unless there's some
specific reason it needs to be mutable (i.e. you're going to change it)
or immutable (i.e. you're going to use it as a dictionary key).
 
J

John Roth

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top