Issue 32501: Documentation for dir([object]) (original) (raw)
Documentation page [1] says "If the object has a method named dir(), this method will be called and must return the list of attributes.".
It seems that on Python 3.6 it only works if the class has a method named dir. Should the documentation be changed?
Microsoft Windows [Version 10.0.16299.192] (c) 2017 Microsoft Corporation. All rights reserved.
D:\Users\wlad>python Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.
class C: pass ... x = C() import types x.dir = types.MethodType(lambda _:[], x) dir(x) ['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref'] C.dir = types.MethodType(lambda _:[], x) dir(x) []
[1] https://docs.python.org/3/library/functions.html
I'm not sure, but the discussion I remember was that it would require changes to an awful lot of places in the docs that would make the docs harder to read. It is very seldom in normal Python coding that an object has a method that it does not get from its class, and by the time you get to the level where you are adding methods to instances it is likely you know about dunder methods only being looked up on classes. Usually you learn about it the first time you try to put a dunder method on an instance, and you scratch your head for a while, and then you find out...but complicating the docs to mention this at every turn would be...excessive, I think. But again, I'm not 100% sure I'm remembering the outcome of that conversation, and I can't remember where it took place (it was an issue in this tracker, but I don't know which one.)
My thanks to David for the clarification. I don't find the logic he describes (but does not necessarily subscribe to!) persuasive in this case. In my opinion, "Let's be incorrect for the sake of simplicity," is not the way to document a programming language in the language's official library documentation.
I think that saying, "If the object (technically the class) has a method named..." would add very little burden to people who don't care about the difference.