
On 2021-05-06 at 18:34:55 -0000, Shreyan Avigyan <pythonshreyan09@gmail.com> wrote:
Chris:
I'm not sure about other people, but I have never, not once, used @property as a means of controlling access. So giving me another way to do something that I am not, and don't want to, do... isn't much of an argument. :)
Ok. I'm giving you another example that doesn't cause security issues but instead instability. Consider this,
class A: def __init__(self, name): self.name = name def create_file(self): with open(name, "a") as file: name.write("something")
At the risk of summoning Muphry's Law, ITYM file.write.
Now consider this,
[1]: x = A("Name") [2]: x.create_file() # Creates a file named "Name" [3]: x.name = "name" [4]: x.create_file() # Creates a file named "name"
We never created a object for "name" but still there's a file named "name" out there. This is the work of read-only attribute. They prevent such instability issues.
What if I do this: [1]: x = A("arbitrary-string") [2]: x.create_file = lambda: os.unlink(self.name) [3]: x.create_file() # Creates a file named "arbitrary-string" We did create an object for "arbitrary-string" (and invoked it, too) but now there's no such file out there. Should I file a bug report against class A? *wink* This is the work of un-pythonicity. If that attribute is that important, then call it _name instead of name, or make it a property without a setter, or implement setattr as appropriate, or document it as read-only outside of A.__init__. Or even more than one of the above. Then line [3] of your example violates the stated and/or implied API, and is a bug. Python is a Consenting Adults language; if it hurts when you do that, then it's on you not to do that, or at least to report an actual case where it hurt. There are already mechanisms to design, document, and implement mostly read-only data (stipulated: allegedly 100% fool proof solutions never seem to work out that way).