PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Objects/moduleobject.c

https://github.com/albertz/CPython
C | 830 lines | 702 code | 78 blank | 50 comment | 194 complexity | 58716b26fecf6f584fe2fdda675cd2ff MD5 | raw file
  1. /* Module object implementation */
  2. #include "Python.h"
  3. #include "internal/pystate.h"
  4. #include "structmember.h"
  5. static Py_ssize_t max_module_number;
  6. typedef struct {
  7. PyObject_HEAD
  8. PyObject *md_dict;
  9. struct PyModuleDef *md_def;
  10. void *md_state;
  11. PyObject *md_weaklist;
  12. PyObject *md_name; /* for logging purposes after md_dict is cleared */
  13. } PyModuleObject;
  14. static PyMemberDef module_members[] = {
  15. {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
  16. {0}
  17. };
  18. /* Helper for sanity check for traverse not handling m_state == NULL
  19. * Issue #32374 */
  20. #ifdef Py_DEBUG
  21. static int
  22. bad_traverse_test(PyObject *self, void *arg) {
  23. assert(self != NULL);
  24. return 0;
  25. }
  26. #endif
  27. PyTypeObject PyModuleDef_Type = {
  28. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  29. "moduledef", /* tp_name */
  30. sizeof(struct PyModuleDef), /* tp_basicsize */
  31. 0, /* tp_itemsize */
  32. };
  33. PyObject*
  34. PyModuleDef_Init(struct PyModuleDef* def)
  35. {
  36. if (PyType_Ready(&PyModuleDef_Type) < 0)
  37. return NULL;
  38. if (def->m_base.m_index == 0) {
  39. max_module_number++;
  40. Py_REFCNT(def) = 1;
  41. Py_TYPE(def) = &PyModuleDef_Type;
  42. def->m_base.m_index = max_module_number;
  43. }
  44. return (PyObject*)def;
  45. }
  46. static int
  47. module_init_dict(PyModuleObject *mod, PyObject *md_dict,
  48. PyObject *name, PyObject *doc)
  49. {
  50. _Py_IDENTIFIER(__name__);
  51. _Py_IDENTIFIER(__doc__);
  52. _Py_IDENTIFIER(__package__);
  53. _Py_IDENTIFIER(__loader__);
  54. _Py_IDENTIFIER(__spec__);
  55. if (md_dict == NULL)
  56. return -1;
  57. if (doc == NULL)
  58. doc = Py_None;
  59. if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0)
  60. return -1;
  61. if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0)
  62. return -1;
  63. if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0)
  64. return -1;
  65. if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0)
  66. return -1;
  67. if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0)
  68. return -1;
  69. if (PyUnicode_CheckExact(name)) {
  70. Py_INCREF(name);
  71. Py_XSETREF(mod->md_name, name);
  72. }
  73. return 0;
  74. }
  75. PyObject *
  76. PyModule_NewObject(PyObject *name)
  77. {
  78. PyModuleObject *m;
  79. m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
  80. if (m == NULL)
  81. return NULL;
  82. m->md_def = NULL;
  83. m->md_state = NULL;
  84. m->md_weaklist = NULL;
  85. m->md_name = NULL;
  86. m->md_dict = PyDict_New();
  87. if (module_init_dict(m, m->md_dict, name, NULL) != 0)
  88. goto fail;
  89. PyObject_GC_Track(m);
  90. return (PyObject *)m;
  91. fail:
  92. Py_DECREF(m);
  93. return NULL;
  94. }
  95. PyObject *
  96. PyModule_New(const char *name)
  97. {
  98. PyObject *nameobj, *module;
  99. nameobj = PyUnicode_FromString(name);
  100. if (nameobj == NULL)
  101. return NULL;
  102. module = PyModule_NewObject(nameobj);
  103. Py_DECREF(nameobj);
  104. return module;
  105. }
  106. /* Check API/ABI version
  107. * Issues a warning on mismatch, which is usually not fatal.
  108. * Returns 0 if an exception is raised.
  109. */
  110. static int
  111. check_api_version(const char *name, int module_api_version)
  112. {
  113. if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
  114. int err;
  115. err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  116. "Python C API version mismatch for module %.100s: "
  117. "This Python has API version %d, module %.100s has version %d.",
  118. name,
  119. PYTHON_API_VERSION, name, module_api_version);
  120. if (err)
  121. return 0;
  122. }
  123. return 1;
  124. }
  125. static int
  126. _add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
  127. {
  128. PyObject *func;
  129. PyMethodDef *fdef;
  130. for (fdef = functions; fdef->ml_name != NULL; fdef++) {
  131. if ((fdef->ml_flags & METH_CLASS) ||
  132. (fdef->ml_flags & METH_STATIC)) {
  133. PyErr_SetString(PyExc_ValueError,
  134. "module functions cannot set"
  135. " METH_CLASS or METH_STATIC");
  136. return -1;
  137. }
  138. func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
  139. if (func == NULL) {
  140. return -1;
  141. }
  142. if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
  143. Py_DECREF(func);
  144. return -1;
  145. }
  146. Py_DECREF(func);
  147. }
  148. return 0;
  149. }
  150. PyObject *
  151. PyModule_Create2(struct PyModuleDef* module, int module_api_version)
  152. {
  153. if (!_PyImport_IsInitialized(PyThreadState_GET()->interp))
  154. Py_FatalError("Python import machinery not initialized");
  155. return _PyModule_CreateInitialized(module, module_api_version);
  156. }
  157. PyObject *
  158. _PyModule_CreateInitialized(struct PyModuleDef* module, int module_api_version)
  159. {
  160. const char* name;
  161. PyModuleObject *m;
  162. if (!PyModuleDef_Init(module))
  163. return NULL;
  164. name = module->m_name;
  165. if (!check_api_version(name, module_api_version)) {
  166. return NULL;
  167. }
  168. if (module->m_slots) {
  169. PyErr_Format(
  170. PyExc_SystemError,
  171. "module %s: PyModule_Create is incompatible with m_slots", name);
  172. return NULL;
  173. }
  174. /* Make sure name is fully qualified.
  175. This is a bit of a hack: when the shared library is loaded,
  176. the module name is "package.module", but the module calls
  177. PyModule_Create*() with just "module" for the name. The shared
  178. library loader squirrels away the true name of the module in
  179. _Py_PackageContext, and PyModule_Create*() will substitute this
  180. (if the name actually matches).
  181. */
  182. if (_Py_PackageContext != NULL) {
  183. const char *p = strrchr(_Py_PackageContext, '.');
  184. if (p != NULL && strcmp(module->m_name, p+1) == 0) {
  185. name = _Py_PackageContext;
  186. _Py_PackageContext = NULL;
  187. }
  188. }
  189. if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
  190. return NULL;
  191. if (module->m_size > 0) {
  192. m->md_state = PyMem_MALLOC(module->m_size);
  193. if (!m->md_state) {
  194. PyErr_NoMemory();
  195. Py_DECREF(m);
  196. return NULL;
  197. }
  198. memset(m->md_state, 0, module->m_size);
  199. }
  200. if (module->m_methods != NULL) {
  201. if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
  202. Py_DECREF(m);
  203. return NULL;
  204. }
  205. }
  206. if (module->m_doc != NULL) {
  207. if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
  208. Py_DECREF(m);
  209. return NULL;
  210. }
  211. }
  212. m->md_def = module;
  213. return (PyObject*)m;
  214. }
  215. PyObject *
  216. PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version)
  217. {
  218. PyModuleDef_Slot* cur_slot;
  219. PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
  220. PyObject *nameobj;
  221. PyObject *m = NULL;
  222. int has_execution_slots = 0;
  223. const char *name;
  224. int ret;
  225. PyModuleDef_Init(def);
  226. nameobj = PyObject_GetAttrString(spec, "name");
  227. if (nameobj == NULL) {
  228. return NULL;
  229. }
  230. name = PyUnicode_AsUTF8(nameobj);
  231. if (name == NULL) {
  232. goto error;
  233. }
  234. if (!check_api_version(name, module_api_version)) {
  235. goto error;
  236. }
  237. if (def->m_size < 0) {
  238. PyErr_Format(
  239. PyExc_SystemError,
  240. "module %s: m_size may not be negative for multi-phase initialization",
  241. name);
  242. goto error;
  243. }
  244. for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
  245. if (cur_slot->slot == Py_mod_create) {
  246. if (create) {
  247. PyErr_Format(
  248. PyExc_SystemError,
  249. "module %s has multiple create slots",
  250. name);
  251. goto error;
  252. }
  253. create = cur_slot->value;
  254. } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) {
  255. PyErr_Format(
  256. PyExc_SystemError,
  257. "module %s uses unknown slot ID %i",
  258. name, cur_slot->slot);
  259. goto error;
  260. } else {
  261. has_execution_slots = 1;
  262. }
  263. }
  264. if (create) {
  265. m = create(spec, def);
  266. if (m == NULL) {
  267. if (!PyErr_Occurred()) {
  268. PyErr_Format(
  269. PyExc_SystemError,
  270. "creation of module %s failed without setting an exception",
  271. name);
  272. }
  273. goto error;
  274. } else {
  275. if (PyErr_Occurred()) {
  276. PyErr_Format(PyExc_SystemError,
  277. "creation of module %s raised unreported exception",
  278. name);
  279. goto error;
  280. }
  281. }
  282. } else {
  283. m = PyModule_NewObject(nameobj);
  284. if (m == NULL) {
  285. goto error;
  286. }
  287. }
  288. if (PyModule_Check(m)) {
  289. ((PyModuleObject*)m)->md_state = NULL;
  290. ((PyModuleObject*)m)->md_def = def;
  291. } else {
  292. if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
  293. PyErr_Format(
  294. PyExc_SystemError,
  295. "module %s is not a module object, but requests module state",
  296. name);
  297. goto error;
  298. }
  299. if (has_execution_slots) {
  300. PyErr_Format(
  301. PyExc_SystemError,
  302. "module %s specifies execution slots, but did not create "
  303. "a ModuleType instance",
  304. name);
  305. goto error;
  306. }
  307. }
  308. if (def->m_methods != NULL) {
  309. ret = _add_methods_to_object(m, nameobj, def->m_methods);
  310. if (ret != 0) {
  311. goto error;
  312. }
  313. }
  314. if (def->m_doc != NULL) {
  315. ret = PyModule_SetDocString(m, def->m_doc);
  316. if (ret != 0) {
  317. goto error;
  318. }
  319. }
  320. /* Sanity check for traverse not handling m_state == NULL
  321. * This doesn't catch all possible cases, but in many cases it should
  322. * make many cases of invalid code crash or raise Valgrind issues
  323. * sooner than they would otherwise.
  324. * Issue #32374 */
  325. #ifdef Py_DEBUG
  326. if (def->m_traverse != NULL) {
  327. def->m_traverse(m, bad_traverse_test, NULL);
  328. }
  329. #endif
  330. Py_DECREF(nameobj);
  331. return m;
  332. error:
  333. Py_DECREF(nameobj);
  334. Py_XDECREF(m);
  335. return NULL;
  336. }
  337. int
  338. PyModule_ExecDef(PyObject *module, PyModuleDef *def)
  339. {
  340. PyModuleDef_Slot *cur_slot;
  341. const char *name;
  342. int ret;
  343. name = PyModule_GetName(module);
  344. if (name == NULL) {
  345. return -1;
  346. }
  347. if (def->m_size >= 0) {
  348. PyModuleObject *md = (PyModuleObject*)module;
  349. if (md->md_state == NULL) {
  350. /* Always set a state pointer; this serves as a marker to skip
  351. * multiple initialization (importlib.reload() is no-op) */
  352. md->md_state = PyMem_MALLOC(def->m_size);
  353. if (!md->md_state) {
  354. PyErr_NoMemory();
  355. return -1;
  356. }
  357. memset(md->md_state, 0, def->m_size);
  358. }
  359. }
  360. if (def->m_slots == NULL) {
  361. return 0;
  362. }
  363. for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
  364. switch (cur_slot->slot) {
  365. case Py_mod_create:
  366. /* handled in PyModule_FromDefAndSpec2 */
  367. break;
  368. case Py_mod_exec:
  369. ret = ((int (*)(PyObject *))cur_slot->value)(module);
  370. if (ret != 0) {
  371. if (!PyErr_Occurred()) {
  372. PyErr_Format(
  373. PyExc_SystemError,
  374. "execution of module %s failed without setting an exception",
  375. name);
  376. }
  377. return -1;
  378. }
  379. if (PyErr_Occurred()) {
  380. PyErr_Format(
  381. PyExc_SystemError,
  382. "execution of module %s raised unreported exception",
  383. name);
  384. return -1;
  385. }
  386. break;
  387. default:
  388. PyErr_Format(
  389. PyExc_SystemError,
  390. "module %s initialized with unknown slot %i",
  391. name, cur_slot->slot);
  392. return -1;
  393. }
  394. }
  395. return 0;
  396. }
  397. int
  398. PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
  399. {
  400. int res;
  401. PyObject *name = PyModule_GetNameObject(m);
  402. if (name == NULL) {
  403. return -1;
  404. }
  405. res = _add_methods_to_object(m, name, functions);
  406. Py_DECREF(name);
  407. return res;
  408. }
  409. int
  410. PyModule_SetDocString(PyObject *m, const char *doc)
  411. {
  412. PyObject *v;
  413. _Py_IDENTIFIER(__doc__);
  414. v = PyUnicode_FromString(doc);
  415. if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) {
  416. Py_XDECREF(v);
  417. return -1;
  418. }
  419. Py_DECREF(v);
  420. return 0;
  421. }
  422. PyObject *
  423. PyModule_GetDict(PyObject *m)
  424. {
  425. PyObject *d;
  426. if (!PyModule_Check(m)) {
  427. PyErr_BadInternalCall();
  428. return NULL;
  429. }
  430. d = ((PyModuleObject *)m) -> md_dict;
  431. assert(d != NULL);
  432. return d;
  433. }
  434. PyObject*
  435. PyModule_GetNameObject(PyObject *m)
  436. {
  437. _Py_IDENTIFIER(__name__);
  438. PyObject *d;
  439. PyObject *name;
  440. if (!PyModule_Check(m)) {
  441. PyErr_BadArgument();
  442. return NULL;
  443. }
  444. d = ((PyModuleObject *)m)->md_dict;
  445. if (d == NULL ||
  446. (name = _PyDict_GetItemId(d, &PyId___name__)) == NULL ||
  447. !PyUnicode_Check(name))
  448. {
  449. PyErr_SetString(PyExc_SystemError, "nameless module");
  450. return NULL;
  451. }
  452. Py_INCREF(name);
  453. return name;
  454. }
  455. const char *
  456. PyModule_GetName(PyObject *m)
  457. {
  458. PyObject *name = PyModule_GetNameObject(m);
  459. if (name == NULL)
  460. return NULL;
  461. Py_DECREF(name); /* module dict has still a reference */
  462. return PyUnicode_AsUTF8(name);
  463. }
  464. PyObject*
  465. PyModule_GetFilenameObject(PyObject *m)
  466. {
  467. _Py_IDENTIFIER(__file__);
  468. PyObject *d;
  469. PyObject *fileobj;
  470. if (!PyModule_Check(m)) {
  471. PyErr_BadArgument();
  472. return NULL;
  473. }
  474. d = ((PyModuleObject *)m)->md_dict;
  475. if (d == NULL ||
  476. (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL ||
  477. !PyUnicode_Check(fileobj))
  478. {
  479. PyErr_SetString(PyExc_SystemError, "module filename missing");
  480. return NULL;
  481. }
  482. Py_INCREF(fileobj);
  483. return fileobj;
  484. }
  485. const char *
  486. PyModule_GetFilename(PyObject *m)
  487. {
  488. PyObject *fileobj;
  489. const char *utf8;
  490. fileobj = PyModule_GetFilenameObject(m);
  491. if (fileobj == NULL)
  492. return NULL;
  493. utf8 = PyUnicode_AsUTF8(fileobj);
  494. Py_DECREF(fileobj); /* module dict has still a reference */
  495. return utf8;
  496. }
  497. PyModuleDef*
  498. PyModule_GetDef(PyObject* m)
  499. {
  500. if (!PyModule_Check(m)) {
  501. PyErr_BadArgument();
  502. return NULL;
  503. }
  504. return ((PyModuleObject *)m)->md_def;
  505. }
  506. void*
  507. PyModule_GetState(PyObject* m)
  508. {
  509. if (!PyModule_Check(m)) {
  510. PyErr_BadArgument();
  511. return NULL;
  512. }
  513. return ((PyModuleObject *)m)->md_state;
  514. }
  515. void
  516. _PyModule_Clear(PyObject *m)
  517. {
  518. PyObject *d = ((PyModuleObject *)m)->md_dict;
  519. if (d != NULL)
  520. _PyModule_ClearDict(d);
  521. }
  522. void
  523. _PyModule_ClearDict(PyObject *d)
  524. {
  525. /* To make the execution order of destructors for global
  526. objects a bit more predictable, we first zap all objects
  527. whose name starts with a single underscore, before we clear
  528. the entire dictionary. We zap them by replacing them with
  529. None, rather than deleting them from the dictionary, to
  530. avoid rehashing the dictionary (to some extent). */
  531. Py_ssize_t pos;
  532. PyObject *key, *value;
  533. /* First, clear only names starting with a single underscore */
  534. pos = 0;
  535. while (PyDict_Next(d, &pos, &key, &value)) {
  536. if (value != Py_None && PyUnicode_Check(key)) {
  537. if (PyUnicode_READ_CHAR(key, 0) == '_' &&
  538. PyUnicode_READ_CHAR(key, 1) != '_') {
  539. if (Py_VerboseFlag > 1) {
  540. const char *s = PyUnicode_AsUTF8(key);
  541. if (s != NULL)
  542. PySys_WriteStderr("# clear[1] %s\n", s);
  543. else
  544. PyErr_Clear();
  545. }
  546. if (PyDict_SetItem(d, key, Py_None) != 0)
  547. PyErr_Clear();
  548. }
  549. }
  550. }
  551. /* Next, clear all names except for __builtins__ */
  552. pos = 0;
  553. while (PyDict_Next(d, &pos, &key, &value)) {
  554. if (value != Py_None && PyUnicode_Check(key)) {
  555. if (PyUnicode_READ_CHAR(key, 0) != '_' ||
  556. !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
  557. {
  558. if (Py_VerboseFlag > 1) {
  559. const char *s = PyUnicode_AsUTF8(key);
  560. if (s != NULL)
  561. PySys_WriteStderr("# clear[2] %s\n", s);
  562. else
  563. PyErr_Clear();
  564. }
  565. if (PyDict_SetItem(d, key, Py_None) != 0)
  566. PyErr_Clear();
  567. }
  568. }
  569. }
  570. /* Note: we leave __builtins__ in place, so that destructors
  571. of non-global objects defined in this module can still use
  572. builtins, in particularly 'None'. */
  573. }
  574. /*[clinic input]
  575. class module "PyModuleObject *" "&PyModule_Type"
  576. [clinic start generated code]*/
  577. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3e35d4f708ecb6af]*/
  578. #include "clinic/moduleobject.c.h"
  579. /* Methods */
  580. /*[clinic input]
  581. module.__init__
  582. name: unicode
  583. doc: object = None
  584. Create a module object.
  585. The name must be a string; the optional doc argument can have any type.
  586. [clinic start generated code]*/
  587. static int
  588. module___init___impl(PyModuleObject *self, PyObject *name, PyObject *doc)
  589. /*[clinic end generated code: output=e7e721c26ce7aad7 input=57f9e177401e5e1e]*/
  590. {
  591. PyObject *dict = self->md_dict;
  592. if (dict == NULL) {
  593. dict = PyDict_New();
  594. if (dict == NULL)
  595. return -1;
  596. self->md_dict = dict;
  597. }
  598. if (module_init_dict(self, dict, name, doc) < 0)
  599. return -1;
  600. return 0;
  601. }
  602. static void
  603. module_dealloc(PyModuleObject *m)
  604. {
  605. PyObject_GC_UnTrack(m);
  606. if (Py_VerboseFlag && m->md_name) {
  607. PySys_FormatStderr("# destroy %S\n", m->md_name);
  608. }
  609. if (m->md_weaklist != NULL)
  610. PyObject_ClearWeakRefs((PyObject *) m);
  611. if (m->md_def && m->md_def->m_free)
  612. m->md_def->m_free(m);
  613. Py_XDECREF(m->md_dict);
  614. Py_XDECREF(m->md_name);
  615. if (m->md_state != NULL)
  616. PyMem_FREE(m->md_state);
  617. Py_TYPE(m)->tp_free((PyObject *)m);
  618. }
  619. static PyObject *
  620. module_repr(PyModuleObject *m)
  621. {
  622. PyThreadState *tstate = PyThreadState_GET();
  623. PyInterpreterState *interp = tstate->interp;
  624. return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
  625. }
  626. static PyObject*
  627. module_getattro(PyModuleObject *m, PyObject *name)
  628. {
  629. PyObject *attr, *mod_name, *getattr;
  630. attr = PyObject_GenericGetAttr((PyObject *)m, name);
  631. if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError)) {
  632. return attr;
  633. }
  634. PyErr_Clear();
  635. if (m->md_dict) {
  636. _Py_IDENTIFIER(__getattr__);
  637. getattr = _PyDict_GetItemId(m->md_dict, &PyId___getattr__);
  638. if (getattr) {
  639. PyObject* stack[1] = {name};
  640. return _PyObject_FastCall(getattr, stack, 1);
  641. }
  642. _Py_IDENTIFIER(__name__);
  643. mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__);
  644. if (mod_name && PyUnicode_Check(mod_name)) {
  645. PyErr_Format(PyExc_AttributeError,
  646. "module '%U' has no attribute '%U'", mod_name, name);
  647. return NULL;
  648. }
  649. }
  650. PyErr_Format(PyExc_AttributeError,
  651. "module has no attribute '%U'", name);
  652. return NULL;
  653. }
  654. static int
  655. module_traverse(PyModuleObject *m, visitproc visit, void *arg)
  656. {
  657. if (m->md_def && m->md_def->m_traverse) {
  658. int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
  659. if (res)
  660. return res;
  661. }
  662. Py_VISIT(m->md_dict);
  663. return 0;
  664. }
  665. static int
  666. module_clear(PyModuleObject *m)
  667. {
  668. if (m->md_def && m->md_def->m_clear) {
  669. int res = m->md_def->m_clear((PyObject*)m);
  670. if (res)
  671. return res;
  672. }
  673. Py_CLEAR(m->md_dict);
  674. return 0;
  675. }
  676. static PyObject *
  677. module_dir(PyObject *self, PyObject *args)
  678. {
  679. _Py_IDENTIFIER(__dict__);
  680. PyObject *result = NULL;
  681. PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
  682. if (dict != NULL) {
  683. if (PyDict_Check(dict)) {
  684. PyObject *dirfunc = PyDict_GetItemString(dict, "__dir__");
  685. if (dirfunc) {
  686. result = _PyObject_CallNoArg(dirfunc);
  687. }
  688. else {
  689. result = PyDict_Keys(dict);
  690. }
  691. }
  692. else {
  693. const char *name = PyModule_GetName(self);
  694. if (name)
  695. PyErr_Format(PyExc_TypeError,
  696. "%.200s.__dict__ is not a dictionary",
  697. name);
  698. }
  699. }
  700. Py_XDECREF(dict);
  701. return result;
  702. }
  703. static PyMethodDef module_methods[] = {
  704. {"__dir__", module_dir, METH_NOARGS,
  705. PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
  706. {0}
  707. };
  708. PyTypeObject PyModule_Type = {
  709. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  710. "module", /* tp_name */
  711. sizeof(PyModuleObject), /* tp_basicsize */
  712. 0, /* tp_itemsize */
  713. (destructor)module_dealloc, /* tp_dealloc */
  714. 0, /* tp_print */
  715. 0, /* tp_getattr */
  716. 0, /* tp_setattr */
  717. 0, /* tp_reserved */
  718. (reprfunc)module_repr, /* tp_repr */
  719. 0, /* tp_as_number */
  720. 0, /* tp_as_sequence */
  721. 0, /* tp_as_mapping */
  722. 0, /* tp_hash */
  723. 0, /* tp_call */
  724. 0, /* tp_str */
  725. (getattrofunc)module_getattro, /* tp_getattro */
  726. PyObject_GenericSetAttr, /* tp_setattro */
  727. 0, /* tp_as_buffer */
  728. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  729. Py_TPFLAGS_BASETYPE, /* tp_flags */
  730. module___init____doc__, /* tp_doc */
  731. (traverseproc)module_traverse, /* tp_traverse */
  732. (inquiry)module_clear, /* tp_clear */
  733. 0, /* tp_richcompare */
  734. offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
  735. 0, /* tp_iter */
  736. 0, /* tp_iternext */
  737. module_methods, /* tp_methods */
  738. module_members, /* tp_members */
  739. 0, /* tp_getset */
  740. 0, /* tp_base */
  741. 0, /* tp_dict */
  742. 0, /* tp_descr_get */
  743. 0, /* tp_descr_set */
  744. offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
  745. module___init__, /* tp_init */
  746. PyType_GenericAlloc, /* tp_alloc */
  747. PyType_GenericNew, /* tp_new */
  748. PyObject_GC_Del, /* tp_free */
  749. };