A further point to Steve's example is that a proxy object like the one he
described would probably have to change its implementation ever so slightly
in order to work as expected in a multi-step lookup involving namespaces
(so that the `wrap` function is only applied to the final value at the end).
Probably something like this:
from types import NamespaceType # similar to FunctionType
class proxy:
….
def __getattr__(self, name):
if isinstance(value := getattr(self.object, name), NamespaceType):
return type(self)(value) # create another proxy object for the
next lookup
return wrap(value)
On Sun, May 2, 2021 at 10:45 AM Matt del Valle <[email protected]> wrote:
> This shouldn't be a problem.
>
> For instance:
>
> class Wrapped:
> namespace foo:
> bar = True
>
> facade = proxy(Wrapped())
> facade.foo.bar # True
>
> Basically, when you try to look up 'foo' on the proxy object, the
> '__getattr__' returns the namespace object, which then forwards on the
> second attribute lookup ('bar') to the 'Wrapped' class. It happens in two
> steps rather than one. So what actually gets looked up is
> vars(wrapped_instance)['foo.bar'], because the 'foo' object that is left
> behind by the namespace block forwards the attribute lookup on to the
> Wrapped class (while prepending itself to the dict lookup).
>
> Does that make sense?
>
> On Sun, May 2, 2021 at 10:30 AM Stestagg <[email protected]> wrote:
>
>>
>>
>> On Sun, 2 May 2021 at 00:57, Matt del Valle <[email protected]> wrote:
>>
>>> Hi all!
>>>
>>> So this is a proposal for a new soft language keyword:
>>>
>>> namespace
>>>
>>> …
>>> - any name bound within the namespace block is bound in exactly the same
>>> way it would be bound if the namespace block were not there, except that
>>> the namespace's name and a dot are prepended to the key when being inserted
>>> into the module/class/locals dict.
>>>
>>
>> Sometimes it’s useful to write classes that are similar to:
>>
>> class proxy:
>> ….
>> def __getattr__(self, name):
>> return wrap(getattr(self.object, name))
>>
>> How would this pattern interact with objects that use namespaces? I’m
>> guessing the interpreter wouldn’t know to call getattr with ‘ns.attr’
>> rather than just ‘ns’?
>>
>> Steve
>>
>>>
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/YSW5QQXTLMVFOJSKHPS7X27HPJUHBTLY/
Code of Conduct: http://python.org/psf/codeofconduct/