The two ways you proposed are both good ideas. Let me throw in one more: tuples! Tuples are immutable.
@property
def bananas(self):
return tuple(self._bananas)
Now that you have these alternative, there are a couple of things of things to keep in mind while choosing one over the other:
- Is the list small and are you okay with a O(n) accessor? Choose tuple. For most part the consumer is not going to see a difference. (Unless of course he tries to mutate it)
- Does the list bananas need some special abilities that a generic
listis falling short on? Subclass a list and raise exceptions on mutating functions. [1]
[1]: jsbueno has a nice ReadOnlyList implementationnice ReadOnlyList implementation that doesn't have the O(n) overhead.