0
class Foo:
    def __init__(self, data: list):
        self._data = data
    
    @property
    def data(self):
        return self._data

Doing this prevents from assignments like obj.data = [1, 2, 3], but it is still possible to modify it with obj.data.append(10) because lists are mutable. There's no problem for being able to modify it from obj._data, but I don't want it to be mutable from obj.data.

One thing I tried is making a copy of _data and then returning it

class Foo:
    def __init__(self, data: list):
        self._data = data
    
    @property
    def data(self):
        copy = self._data[:]
        return copy

but I'm not sure if this is the best way to do it, are there any other alternative ways?

8
  • "best way" measured how? Commented Oct 5, 2023 at 17:58
  • 1
    You can use tuple instead of a list. Commented Oct 5, 2023 at 17:58
  • if you are using a list, it will be mutable. There is nothing you can do to change that. You can, of course, use something other than a list, or return a copy like you have in the question Commented Oct 5, 2023 at 18:02
  • @ScottHunter whatever is considered best practice Commented Oct 5, 2023 at 18:05
  • @AndrejKesely what if it's a dict? Commented Oct 5, 2023 at 18:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.