title: How is __dir__ implemented exactly, and how should I know it?
body: <p>So I'm trying to know the details of <code>dir()</code> function. First I looked at the implementation of it:
  <a href="https://github.com/python/cpython/blob/e76daebc0c8afa3981a4c5a8b54537f756e805de/Objects/object.c#L1450-L1477" rel="nofollow noreferrer">https://github.com/python/cpython/blob/e76daebc0c8afa3981a4c5a8b54537f756e805de/Objects/object.c#L1450-L1477</a></p>
  
  <pre class="lang-c prettyprint-override"><code>/* Helper for PyObject_Dir: object introspection. */
  static PyObject *
  _dir_object(PyObject *obj)
  {
      PyObject *result, *sorted;
      PyObject *dirfunc = _PyObject_LookupSpecial(obj, &amp;PyId___dir__);
  
      assert(obj);
      if (dirfunc == NULL) {
          if (!PyErr_Occurred())
              PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
          return NULL;
      }
      /* use __dir__ */
      result = _PyObject_CallNoArg(dirfunc);
      Py_DECREF(dirfunc);
      if (result == NULL)
          return NULL;
      /* return sorted(result) */
      sorted = PySequence_List(result);
      Py_DECREF(result);
      if (sorted == NULL)
          return NULL;
      if (PyList_Sort(sorted)) {
          Py_DECREF(sorted);
          return NULL;
      }
      return sorted;
  }
  </code></pre>
  
  <p>And found that the <code>_dir_object</code> function doesn't do any work itself, but invokes the <code>__dir__</code> method of the introspected object. </p>
  
  <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; def test(): pass
  &gt;&gt;&gt; test.__dir__
  &lt;built-in method __dir__ of function object at 0x10ee57ae8&gt;
  </code></pre>
  
  <p>So how to know the implementation of it?</p>