PEP Idea: Real private attribute

Mehrzad Saremi mehrzad.1024 at gmail.com
Sun Aug 29 21:08:11 EDT 2021


The proposed semantics would be the same as self.__privs__[__class__,
"foo"]; yes I can say the problem is ugliness. The following is an example
where name mangling can be problematic (of course there are workarounds,
yet if double-underscores are meant to represent class-specific members,
the following behavior is an infringement of the purpose).

```
class Weighable:
def weight(self):
raise NotImplementedError()


class AddWeight:
def __init__(self, weight):
self.weight = weight

def __call__(self, cls):
class Wrapper(cls, Weighable):
__weight = self.weight

def weight(self):
return self.__weight + (cls.weight(self) if issubclass(cls, Weighable) else
0)  # Unexpected behavior

return Wrapper


@AddWeight(2.0)
@AddWeight(1.0)
class C:
pass


print(C().weight())
```

> If the parent class isn't aware which class you're in, how is the
language going to define it?

I mean if you want to implement self.__privs__[__class__, "foo"] in a
parent class using __setattr__/__getattribute__ the __class__ value is
unknown.


On Mon, 30 Aug 2021 at 00:26, Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Aug 30, 2021 at 5:49 AM Mehrzad Saremi <mehrzad.1024 at gmail.com>
> wrote:
> >
> > No, a class ("the class that I'm lexically inside") cannot be accessed
> from
> > outside of the class. This is why I'm planning to offer it as a core
> > feature because only the parser would know. There's apparently no elegant
> > solution if you want to implement it yourself. You'll need to write
> > self.__privs__[__class__, "foo"], whenever you want to use the feature
> and
> > even wrapping it in superclasses won't remedy it, because the parent
> class
> > isn't aware which class you're inside. It seems to me name mangling must
> > have been an ad-hoc solution in a language that it doesn't really fit
> when
> > it could have been implemented in a much more cogent way.
> >
>
> If the parent class isn't aware which class you're in, how is the
> language going to define it?
>
> Can you give a full run-down of the semantics of your proposed privs,
> and how it's different from something like you just used above -
> self.__privs__[__class__, "foo"] - ? If the problem is the ugliness
> alone, then say so; but also, how this would work with decorators,
> since you specifically mention them as a use-case.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list