On Thu, May 06, 2021 at 03:09:33PM -0000, Shreyan Avigyan wrote: > What I'm suggesting is that introducing a new keyword or decorator as > required to create a variable that can be modified from within the > class but not outside the class.
That's an interesting suggestion, but how do you define "within the class"? My guess is that you have used a lot of Java, or at least read a lot of Object Oriented Programming theory that is based on the Java model. In Java "inside the class" is easy: it is a method that is written under the class keyword in the same file as the class. The Java compiler can determine statically which methods belong to the class, which to a parent class or a subclass, and can enforce access rules for "private, public, protected" etc. And the consequence is that, anecdotally, Java programmers spend a lot of time fighting the compiler trying to work around overzealous and unnecessary use of private and protected keywords. They usually do that by using reflection: https://sindhitutorials.com/blog/access-private-variables-and-methods-from-another-class-in-java/ Now consider Python. We can, and do, create classes dynamically. For example, we can inject methods into a class at runtime: class Spam(object): pass # Later on def method(self, arg): self._private = arg Spam.method = method The class and the method don't even need to be defined in the same file. We can add methods to instances: from types import MethodType instance = Spam() instance.view = MethodType(lambda self: print(self._private), instance) Both of those are fairly unusual things to do. Maybe less than 1% of classes wouold use those techniques. But a *very* common technique is to use decorators: def decorate(method): def inner(self, arg): # count the number of times the method is called self._counter += 1 return method(self, arg) return inner class Eggs(object): @decorate def method(self, x): do_something_with(x) The important thing here is that at runtime, it is difficult or impossible for the interpreter to tell the difference between a "normal" method which is defined statically inside the class, and a decorated or injected method which came from "outside" the class. It possibly could be done, but only at a significant runtime cost, and it would probably be easy for people to work around. If Python had a "private" keyword that worked as you wanted, it would likely be more of a nuisance than a usual feature, and like Java programmers, we would probably spend too much time working around the overzealous use of the feature. Steve _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/ZFVHDGFPJDVEZ5OTYUDBPYCZUT4LUTLX/ Code of Conduct: http://python.org/psf/codeofconduct/