[Python-Dev] PEP 447: add type.locallookup (original) (raw)

Ronald Oussoren ronaldoussoren at mac.com
Thu Sep 19 11:00:25 CEST 2013


On 13 Sep, 2013, at 18:19, Steve Dower <Steve.Dower at microsoft.com> wrote:

From: Steven D'Aprano

On Fri, Sep 13, 2013 at 04:26:06AM +0000, Steve Dower wrote:

Last I checked, looking up in the instance dict us exactly what it does. Even the example you posted is doing that. The example from the PEP shows: return cls.dict[name] not "self.dict[name]". It is true that "the instance" in this case refers to it being an instance of the metaclass, but that instance is, in fact, a class/type. That's why we normally call it "cls" in a metaclass method rather than "self". Right, but where's the difference between these two? class A: def tdb(self, name): if name == 'someattributeonmyinstanceofA': return itsvalue try: return self.dict[name] except KeyError: raise AttributeError(name) class MetaB: def tdb(cls, name): if name == 'someattributeonmyclassB': return itsvalue try: return cls.dict[name] except KeyError: raise AttributeError(name) (Yes, either of these could be written with getattribute, but that function cannot be called by super().) As I see it, there are two (correct) ways to interpret what this method is for, which influences what it should be called. 1. It directly replaces obj.dict[name] everywhere that is done, including internally in the interpreter. 2. It is the same as getattribute without the final call to object.getattribute I guess it's also correct to view it as a special helper for super(), but it is more generally applicable than that.

It directly replaces cls.dict[name] for object.getattribute and super.getattribute.

The primary reason for writing a proposal is that getattribute can be used to override attribute lookup on an instance, but there is way to override how super() looks up an attribute. Using the method for both super().getattribute and object.getattribute results in a cleaner model than just having a new hook for super().getattribute.

[...]

By the way, I think the PEP should have a more complex example. The SillyObject example is nice and easy to understand, but it doesn't really help with the motivating use-case "dynamic classes that can grow new methods on demand". Ronald, if you're reading this, can you add such an example please? Also, there's a typo in the SillyObject M method ("fourtytwo" should not have a U in it). Agreed. No harm in more examples.

[...]

A full example of where this may realistically be needed is longer and certainly involves metaclasses, but fundamentally it's just the same as getattribute with slightly different semantics.

PyObjC will be a truly realistic example, but that involves loads of fairly complex C code and likely won't help to explain anything beyond (hopefully) showing that this proposal can lead to significant code removal in some situations.

Ronald



More information about the Python-Dev mailing list