s3c
s3c

Reputation: 153

Preventing modification of returned lists in python

I'm working om my python skills and am trying out creating some classes. Since python is reference based any list returned by a class method can be modified by the caller which would then reflect back in the class (as I have it). What would be the correct way of avoiding this? I was thinking either converting the nested list to nested tuples or doing a deep copy?

Upvotes: 3

Views: 242

Answers (1)

Edward Loper
Edward Loper

Reputation: 15944

Returning tuples is a fairly standard way to give back immutable lists. Another option would be to return an immutable "view" of the list. I don't think the stdlib currently contains such a class, so you'd probably have to roll your own, but it would be fairly straight forward. Basically, the class would contain a single private instance variable (the underlying list); and would implement only the read operations (__getitem__, __len__, etc) and would delegate them to the instance variable (wrapping any child items in "view" objects as necessary).

Upvotes: 2

Related Questions