Promoting Python

Ian Kelly ian.g.kelly at gmail.com
Wed Apr 6 17:37:28 EDT 2016


On Wed, Apr 6, 2016 at 2:39 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Ian Kelly <ian.g.kelly at gmail.com>:
>
>> On Wed, Apr 6, 2016 at 1:59 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>>> It seems to me CPython is being a bit too picky here. Why should it
>>> care if the method is a class method or an object method?
>>
>> Because the purpose of a class is to define the behavior of its
>> instances. A function stored in an object attribute technically isn't
>> a method at all. It's just a function that happens to be stored in an
>> object attribute, i.e. *data*. Why should the behavior of a
>> SimpleNamespace change just because somebody decided they wanted to
>> store something under the name "__iter__" (or worse,
>> "__getattribute__")?
>>
>> Also, because not having to check the instance dict for the presence
>> of dunder methods is faster.
>
> Not convinced. Probably just an oversight.

It's documented here:
https://docs.python.org/3/reference/datamodel.html#special-method-lookup

> For example, file-like objects have no such reservations:
>
>     import sys
>     import types
>     import xml.dom.minidom
>
>     filelike = types.SimpleNamespace()
>     def write(s):
>         for c in s:
>             sys.stdout.write("{{{}}}".format(c))
>     filelike.write = write
>     filelike.close = lambda: None
>     doc = xml.dom.minidom.getDOMImplementation().createDocument(
>         None, "tag", None).writexml(filelike)
>     sys.stdout.write("\n")

The minidom implementation is probably just calling
filelike.write('blah'). That will succeed in calling either a method
or a function-in-an-attribute. Note that the write function you
defined in this example has no self argument. This points to the fact
that it's not truly a method.



More information about the Python-list mailing list