blob: 24c5f4c282e8684b69193e206566d8beda165ea5 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Martin v. Löwis1a214512008-06-11 05:26:20 +00007static Py_ssize_t max_module_number;
8
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000010 PyObject_HEAD
11 PyObject *md_dict;
12 struct PyModuleDef *md_def;
13 void *md_state;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020014 PyObject *md_weaklist;
15 PyObject *md_name; /* for logging purposes after md_dict is cleared */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000016} PyModuleObject;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000017
Neil Schemenauerf23473f2001-10-21 22:28:58 +000018static PyMemberDef module_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019 {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
20 {0}
Tim Peters6d6c1a32001-08-02 04:15:00 +000021};
22
Nick Coghland5cacbb2015-05-23 22:24:10 +100023PyTypeObject PyModuleDef_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000024 PyVarObject_HEAD_INIT(&PyType_Type, 0)
25 "moduledef", /* tp_name */
26 sizeof(struct PyModuleDef), /* tp_size */
27 0, /* tp_itemsize */
Martin v. Löwis1a214512008-06-11 05:26:20 +000028};
29
30
Nick Coghland5cacbb2015-05-23 22:24:10 +100031PyObject*
32PyModuleDef_Init(struct PyModuleDef* def)
33{
34 if (PyType_Ready(&PyModuleDef_Type) < 0)
35 return NULL;
36 if (def->m_base.m_index == 0) {
37 max_module_number++;
38 Py_REFCNT(def) = 1;
39 Py_TYPE(def) = &PyModuleDef_Type;
40 def->m_base.m_index = max_module_number;
41 }
42 return (PyObject*)def;
43}
44
Brett Cannon4c14b5d2013-05-04 13:56:58 -040045static int
Antoine Pitroudcedaf62013-07-31 23:14:08 +020046module_init_dict(PyModuleObject *mod, PyObject *md_dict,
47 PyObject *name, PyObject *doc)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040048{
Benjamin Peterson027ce162014-04-24 19:39:18 -040049 _Py_IDENTIFIER(__name__);
50 _Py_IDENTIFIER(__doc__);
51 _Py_IDENTIFIER(__package__);
52 _Py_IDENTIFIER(__loader__);
53 _Py_IDENTIFIER(__spec__);
Serhiy Storchaka009b8112015-03-18 21:53:15 +020054
Brett Cannon4c14b5d2013-05-04 13:56:58 -040055 if (md_dict == NULL)
56 return -1;
57 if (doc == NULL)
58 doc = Py_None;
59
Benjamin Peterson027ce162014-04-24 19:39:18 -040060 if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040061 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040062 if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040063 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040064 if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040065 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040066 if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0)
Brett Cannon4c14b5d2013-05-04 13:56:58 -040067 return -1;
Benjamin Peterson027ce162014-04-24 19:39:18 -040068 if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0)
Eric Snowb523f842013-11-22 09:05:39 -070069 return -1;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020070 if (PyUnicode_CheckExact(name)) {
71 Py_INCREF(name);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +020072 Py_SETREF(mod->md_name, name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +020073 }
Brett Cannon4c14b5d2013-05-04 13:56:58 -040074
75 return 0;
76}
77
78
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079PyObject *
Victor Stinner0639b562011-03-04 12:57:07 +000080PyModule_NewObject(PyObject *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 PyModuleObject *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
84 if (m == NULL)
85 return NULL;
86 m->md_def = NULL;
87 m->md_state = NULL;
Antoine Pitroudcedaf62013-07-31 23:14:08 +020088 m->md_weaklist = NULL;
89 m->md_name = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 m->md_dict = PyDict_New();
Antoine Pitroudcedaf62013-07-31 23:14:08 +020091 if (module_init_dict(m, m->md_dict, name, NULL) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 goto fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 PyObject_GC_Track(m);
94 return (PyObject *)m;
Guido van Rossumc45611d1993-11-17 22:58:56 +000095
96 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 Py_DECREF(m);
98 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099}
100
Martin v. Löwis1a214512008-06-11 05:26:20 +0000101PyObject *
Victor Stinner0639b562011-03-04 12:57:07 +0000102PyModule_New(const char *name)
103{
104 PyObject *nameobj, *module;
105 nameobj = PyUnicode_FromString(name);
106 if (nameobj == NULL)
107 return NULL;
108 module = PyModule_NewObject(nameobj);
109 Py_DECREF(nameobj);
110 return module;
111}
112
Nick Coghland5cacbb2015-05-23 22:24:10 +1000113/* Check API/ABI version
114 * Issues a warning on mismatch, which is usually not fatal.
115 * Returns 0 if an exception is raised.
116 */
117static int
118check_api_version(const char *name, int module_api_version)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000119{
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000120 if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000121 int err;
122 err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
123 "Python C API version mismatch for module %.100s: "
124 "This Python has API version %d, module %.100s has version %d.",
125 name,
126 PYTHON_API_VERSION, name, module_api_version);
127 if (err)
Nick Coghland5cacbb2015-05-23 22:24:10 +1000128 return 0;
129 }
130 return 1;
131}
132
133PyObject *
134PyModule_Create2(struct PyModuleDef* module, int module_api_version)
135{
136 const char* name;
137 PyModuleObject *m;
138 PyInterpreterState *interp = PyThreadState_Get()->interp;
139 if (interp->modules == NULL)
140 Py_FatalError("Python import machinery not initialized");
141 if (!PyModuleDef_Init(module))
142 return NULL;
143 name = module->m_name;
144 if (!check_api_version(name, module_api_version)) {
145 return NULL;
146 }
147 if (module->m_slots) {
148 PyErr_Format(
149 PyExc_SystemError,
150 "module %s: PyModule_Create is incompatible with m_slots", name);
151 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 }
153 /* Make sure name is fully qualified.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 This is a bit of a hack: when the shared library is loaded,
156 the module name is "package.module", but the module calls
157 PyModule_Create*() with just "module" for the name. The shared
158 library loader squirrels away the true name of the module in
159 _Py_PackageContext, and PyModule_Create*() will substitute this
160 (if the name actually matches).
161 */
162 if (_Py_PackageContext != NULL) {
163 char *p = strrchr(_Py_PackageContext, '.');
164 if (p != NULL && strcmp(module->m_name, p+1) == 0) {
165 name = _Py_PackageContext;
166 _Py_PackageContext = NULL;
167 }
168 }
169 if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
170 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (module->m_size > 0) {
173 m->md_state = PyMem_MALLOC(module->m_size);
174 if (!m->md_state) {
175 PyErr_NoMemory();
176 Py_DECREF(m);
177 return NULL;
178 }
179 memset(m->md_state, 0, module->m_size);
180 }
181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (module->m_methods != NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +1000183 if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) {
Meador Inge29e49d62012-07-19 13:45:43 -0500184 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return NULL;
Meador Inge29e49d62012-07-19 13:45:43 -0500186 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 }
188 if (module->m_doc != NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +1000189 if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) {
Meador Inge29e49d62012-07-19 13:45:43 -0500190 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 return NULL;
192 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 }
194 m->md_def = module;
195 return (PyObject*)m;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000196}
197
Nick Coghland5cacbb2015-05-23 22:24:10 +1000198PyObject *
199PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version)
200{
201 PyModuleDef_Slot* cur_slot;
202 PyObject *(*create)(PyObject *, PyModuleDef*) = NULL;
203 PyObject *nameobj;
204 PyObject *m = NULL;
205 int has_execution_slots = 0;
206 char *name;
207 int ret;
208
209 PyModuleDef_Init(def);
210
211 nameobj = PyObject_GetAttrString(spec, "name");
212 if (nameobj == NULL) {
213 return NULL;
214 }
215 name = PyUnicode_AsUTF8(nameobj);
216 if (name == NULL) {
217 goto error;
218 }
219
220 if (!check_api_version(name, module_api_version)) {
221 goto error;
222 }
223
224 if (def->m_size < 0) {
225 PyErr_Format(
226 PyExc_SystemError,
227 "module %s: m_size may not be negative for multi-phase initialization",
228 name);
229 goto error;
230 }
231
232 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
233 if (cur_slot->slot == Py_mod_create) {
234 if (create) {
235 PyErr_Format(
236 PyExc_SystemError,
237 "module %s has multiple create slots",
238 name);
239 goto error;
240 }
241 create = cur_slot->value;
242 } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) {
243 PyErr_Format(
244 PyExc_SystemError,
245 "module %s uses unknown slot ID %i",
246 name, cur_slot->slot);
247 goto error;
248 } else {
249 has_execution_slots = 1;
250 }
251 }
252
253 if (create) {
254 m = create(spec, def);
255 if (m == NULL) {
256 if (!PyErr_Occurred()) {
257 PyErr_Format(
258 PyExc_SystemError,
259 "creation of module %s failed without setting an exception",
260 name);
261 }
262 goto error;
263 } else {
264 if (PyErr_Occurred()) {
265 PyErr_Format(PyExc_SystemError,
266 "creation of module %s raised unreported exception",
267 name);
268 goto error;
269 }
270 }
271 } else {
272 m = PyModule_New(name);
273 if (m == NULL) {
274 goto error;
275 }
276 }
277
278 if (PyModule_Check(m)) {
279 ((PyModuleObject*)m)->md_state = NULL;
280 ((PyModuleObject*)m)->md_def = def;
281 } else {
282 if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) {
283 PyErr_Format(
284 PyExc_SystemError,
285 "module %s is not a module object, but requests module state",
286 name);
287 goto error;
288 }
289 if (has_execution_slots) {
290 PyErr_Format(
291 PyExc_SystemError,
292 "module %s specifies execution slots, but did not create "
293 "a ModuleType instance",
294 name);
295 goto error;
296 }
297 }
298
299 if (def->m_methods != NULL) {
300 ret = PyModule_AddFunctions(m, def->m_methods);
301 if (ret != 0) {
302 goto error;
303 }
304 }
305
306 if (def->m_doc != NULL) {
307 ret = PyModule_SetDocString(m, def->m_doc);
308 if (ret != 0) {
309 goto error;
310 }
311 }
312
Nick Coghlana48db2b2015-05-24 01:03:46 +1000313 Py_DECREF(nameobj);
Nick Coghland5cacbb2015-05-23 22:24:10 +1000314 return m;
315
316error:
317 Py_DECREF(nameobj);
318 Py_XDECREF(m);
319 return NULL;
320}
321
322int
323PyModule_ExecDef(PyObject *module, PyModuleDef *def)
324{
325 PyModuleDef_Slot *cur_slot;
326 const char *name;
327 int ret;
328
329 name = PyModule_GetName(module);
330 if (name == NULL) {
331 return -1;
332 }
333
334 if (PyModule_Check(module) && def->m_size >= 0) {
335 PyModuleObject *md = (PyModuleObject*)module;
336 if (md->md_state == NULL) {
337 /* Always set a state pointer; this serves as a marker to skip
338 * multiple initialization (importlib.reload() is no-op) */
339 md->md_state = PyMem_MALLOC(def->m_size);
340 if (!md->md_state) {
341 PyErr_NoMemory();
342 return -1;
343 }
344 memset(md->md_state, 0, def->m_size);
345 }
346 }
347
348 if (def->m_slots == NULL) {
349 return 0;
350 }
351
352 for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) {
353 switch (cur_slot->slot) {
354 case Py_mod_create:
355 /* handled in PyModule_CreateFromSlots */
356 break;
357 case Py_mod_exec:
358 ret = ((int (*)(PyObject *))cur_slot->value)(module);
359 if (ret != 0) {
360 if (!PyErr_Occurred()) {
361 PyErr_Format(
362 PyExc_SystemError,
363 "execution of module %s failed without setting an exception",
364 name);
365 }
366 return -1;
367 }
368 if (PyErr_Occurred()) {
369 PyErr_Format(
370 PyExc_SystemError,
371 "execution of module %s raised unreported exception",
372 name);
373 return -1;
374 }
375 break;
376 default:
377 PyErr_Format(
378 PyExc_SystemError,
379 "module %s initialized with unknown slot %i",
380 name, cur_slot->slot);
381 return -1;
382 }
383 }
384 return 0;
385}
386
387int
388PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
389{
390 PyObject *name, *func;
391 PyMethodDef *fdef;
392
393 name = PyModule_GetNameObject(m);
394 if (name == NULL) {
395 return -1;
396 }
397
398 for (fdef = functions; fdef->ml_name != NULL; fdef++) {
399 if ((fdef->ml_flags & METH_CLASS) ||
400 (fdef->ml_flags & METH_STATIC)) {
401 PyErr_SetString(PyExc_ValueError,
402 "module functions cannot set"
403 " METH_CLASS or METH_STATIC");
404 Py_DECREF(name);
405 return -1;
406 }
407 func = PyCFunction_NewEx(fdef, (PyObject*)m, name);
408 if (func == NULL) {
409 Py_DECREF(name);
410 return -1;
411 }
412 if (PyObject_SetAttrString(m, fdef->ml_name, func) != 0) {
413 Py_DECREF(func);
414 Py_DECREF(name);
415 return -1;
416 }
417 Py_DECREF(func);
418 }
419 Py_DECREF(name);
420 return 0;
421}
422
423int
424PyModule_SetDocString(PyObject *m, const char *doc)
425{
426 PyObject *v;
427 _Py_IDENTIFIER(__doc__);
428
429 v = PyUnicode_FromString(doc);
430 if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) {
431 Py_XDECREF(v);
432 return -1;
433 }
434 Py_DECREF(v);
435 return 0;
436}
Martin v. Löwis1a214512008-06-11 05:26:20 +0000437
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000439PyModule_GetDict(PyObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *d;
442 if (!PyModule_Check(m)) {
443 PyErr_BadInternalCall();
444 return NULL;
445 }
446 d = ((PyModuleObject *)m) -> md_dict;
447 if (d == NULL)
448 ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
449 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450}
451
Victor Stinnerbd475112011-02-23 00:21:43 +0000452PyObject*
453PyModule_GetNameObject(PyObject *m)
Guido van Rossum0558a201990-10-26 15:00:11 +0000454{
Benjamin Peterson027ce162014-04-24 19:39:18 -0400455 _Py_IDENTIFIER(__name__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *d;
Victor Stinnerbd475112011-02-23 00:21:43 +0000457 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!PyModule_Check(m)) {
459 PyErr_BadArgument();
460 return NULL;
461 }
462 d = ((PyModuleObject *)m)->md_dict;
463 if (d == NULL ||
Benjamin Peterson027ce162014-04-24 19:39:18 -0400464 (name = _PyDict_GetItemId(d, &PyId___name__)) == NULL ||
Victor Stinnerbd475112011-02-23 00:21:43 +0000465 !PyUnicode_Check(name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 {
467 PyErr_SetString(PyExc_SystemError, "nameless module");
468 return NULL;
469 }
Victor Stinnerbd475112011-02-23 00:21:43 +0000470 Py_INCREF(name);
471 return name;
472}
473
474const char *
475PyModule_GetName(PyObject *m)
476{
477 PyObject *name = PyModule_GetNameObject(m);
478 if (name == NULL)
479 return NULL;
480 Py_DECREF(name); /* module dict has still a reference */
481 return _PyUnicode_AsString(name);
Guido van Rossum0558a201990-10-26 15:00:11 +0000482}
483
Victor Stinner6c00c142010-08-17 23:37:11 +0000484PyObject*
485PyModule_GetFilenameObject(PyObject *m)
Guido van Rossum98cc19f1999-02-15 14:47:16 +0000486{
Benjamin Peterson027ce162014-04-24 19:39:18 -0400487 _Py_IDENTIFIER(__file__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject *d;
489 PyObject *fileobj;
490 if (!PyModule_Check(m)) {
491 PyErr_BadArgument();
492 return NULL;
493 }
494 d = ((PyModuleObject *)m)->md_dict;
495 if (d == NULL ||
Benjamin Peterson027ce162014-04-24 19:39:18 -0400496 (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 !PyUnicode_Check(fileobj))
498 {
499 PyErr_SetString(PyExc_SystemError, "module filename missing");
500 return NULL;
501 }
Victor Stinner6c00c142010-08-17 23:37:11 +0000502 Py_INCREF(fileobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return fileobj;
Victor Stinner8124feb2010-05-07 00:50:12 +0000504}
505
506const char *
507PyModule_GetFilename(PyObject *m)
508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 PyObject *fileobj;
Victor Stinner6c00c142010-08-17 23:37:11 +0000510 char *utf8;
511 fileobj = PyModule_GetFilenameObject(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (fileobj == NULL)
513 return NULL;
Victor Stinner6c00c142010-08-17 23:37:11 +0000514 utf8 = _PyUnicode_AsString(fileobj);
Victor Stinnerbd475112011-02-23 00:21:43 +0000515 Py_DECREF(fileobj); /* module dict has still a reference */
Victor Stinner6c00c142010-08-17 23:37:11 +0000516 return utf8;
Guido van Rossum98cc19f1999-02-15 14:47:16 +0000517}
518
Martin v. Löwis1a214512008-06-11 05:26:20 +0000519PyModuleDef*
520PyModule_GetDef(PyObject* m)
521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (!PyModule_Check(m)) {
523 PyErr_BadArgument();
524 return NULL;
525 }
526 return ((PyModuleObject *)m)->md_def;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000527}
528
529void*
530PyModule_GetState(PyObject* m)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (!PyModule_Check(m)) {
533 PyErr_BadArgument();
534 return NULL;
535 }
536 return ((PyModuleObject *)m)->md_state;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000537}
538
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000539void
Fred Drakeee238b92000-07-09 06:03:25 +0000540_PyModule_Clear(PyObject *m)
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000541{
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200542 PyObject *d = ((PyModuleObject *)m)->md_dict;
543 if (d != NULL)
544 _PyModule_ClearDict(d);
545}
546
547void
548_PyModule_ClearDict(PyObject *d)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* To make the execution order of destructors for global
551 objects a bit more predictable, we first zap all objects
552 whose name starts with a single underscore, before we clear
553 the entire dictionary. We zap them by replacing them with
554 None, rather than deleting them from the dictionary, to
555 avoid rehashing the dictionary (to some extent). */
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 Py_ssize_t pos;
558 PyObject *key, *value;
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* First, clear only names starting with a single underscore */
561 pos = 0;
562 while (PyDict_Next(d, &pos, &key, &value)) {
563 if (value != Py_None && PyUnicode_Check(key)) {
Brett Cannon62228db2012-04-29 14:38:11 -0400564 if (PyUnicode_READ_CHAR(key, 0) == '_' &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200565 PyUnicode_READ_CHAR(key, 1) != '_') {
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000566 if (Py_VerboseFlag > 1) {
567 const char *s = _PyUnicode_AsString(key);
568 if (s != NULL)
569 PySys_WriteStderr("# clear[1] %s\n", s);
570 else
571 PyErr_Clear();
572 }
Serhiy Storchaka1f9d11b2014-02-12 09:55:01 +0200573 if (PyDict_SetItem(d, key, Py_None) != 0)
574 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 }
576 }
577 }
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Next, clear all names except for __builtins__ */
580 pos = 0;
581 while (PyDict_Next(d, &pos, &key, &value)) {
582 if (value != Py_None && PyUnicode_Check(key)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200583 if (PyUnicode_READ_CHAR(key, 0) != '_' ||
584 PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
Victor Stinnerf3f22a22010-05-19 00:03:09 +0000585 {
586 if (Py_VerboseFlag > 1) {
587 const char *s = _PyUnicode_AsString(key);
588 if (s != NULL)
589 PySys_WriteStderr("# clear[2] %s\n", s);
590 else
591 PyErr_Clear();
592 }
Serhiy Storchaka1f9d11b2014-02-12 09:55:01 +0200593 if (PyDict_SetItem(d, key, Py_None) != 0)
594 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 }
596 }
597 }
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Note: we leave __builtins__ in place, so that destructors
600 of non-global objects defined in this module can still use
601 builtins, in particularly 'None'. */
Guido van Rossumf1dc0611998-02-19 20:51:52 +0000602
603}
604
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605/* Methods */
606
Tim Peters6d6c1a32001-08-02 04:15:00 +0000607static int
Guido van Rossumc3a787e2002-06-04 05:52:47 +0000608module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 static char *kwlist[] = {"name", "doc", NULL};
611 PyObject *dict, *name = Py_None, *doc = Py_None;
612 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
613 kwlist, &name, &doc))
614 return -1;
615 dict = m->md_dict;
616 if (dict == NULL) {
617 dict = PyDict_New();
618 if (dict == NULL)
619 return -1;
620 m->md_dict = dict;
621 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200622 if (module_init_dict(m, dict, name, doc) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return -1;
624 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000625}
626
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627static void
Fred Drakeee238b92000-07-09 06:03:25 +0000628module_dealloc(PyModuleObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyObject_GC_UnTrack(m);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200631 if (Py_VerboseFlag && m->md_name) {
632 PySys_FormatStderr("# destroy %S\n", m->md_name);
633 }
634 if (m->md_weaklist != NULL)
635 PyObject_ClearWeakRefs((PyObject *) m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (m->md_def && m->md_def->m_free)
637 m->md_def->m_free(m);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200638 Py_XDECREF(m->md_dict);
639 Py_XDECREF(m->md_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (m->md_state != NULL)
641 PyMem_FREE(m->md_state);
642 Py_TYPE(m)->tp_free((PyObject *)m);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643}
644
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000645static PyObject *
Fred Drakeee238b92000-07-09 06:03:25 +0000646module_repr(PyModuleObject *m)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647{
Eric Snowb523f842013-11-22 09:05:39 -0700648 PyThreadState *tstate = PyThreadState_GET();
649 PyInterpreterState *interp = tstate->interp;
Barry Warsaw2907fe62001-08-16 20:39:24 +0000650
Eric Snowb523f842013-11-22 09:05:39 -0700651 return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652}
653
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700654static PyObject*
Benjamin Peterson1184e262014-04-24 19:29:23 -0400655module_getattro(PyModuleObject *m, PyObject *name)
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700656{
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700657 PyObject *attr, *mod_name;
Benjamin Peterson1184e262014-04-24 19:29:23 -0400658 attr = PyObject_GenericGetAttr((PyObject *)m, name);
659 if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError))
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700660 return attr;
661 PyErr_Clear();
Benjamin Peterson1184e262014-04-24 19:29:23 -0400662 if (m->md_dict) {
Benjamin Peterson027ce162014-04-24 19:39:18 -0400663 _Py_IDENTIFIER(__name__);
664 mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__);
Benjamin Peterson1184e262014-04-24 19:29:23 -0400665 if (mod_name) {
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700666 PyErr_Format(PyExc_AttributeError,
667 "module '%U' has no attribute '%U'", mod_name, name);
668 return NULL;
669 }
Benjamin Peterson1184e262014-04-24 19:29:23 -0400670 else if (PyErr_Occurred()) {
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700671 PyErr_Clear();
Benjamin Peterson1184e262014-04-24 19:29:23 -0400672 }
Ethan Furman7b9ff0e2014-04-24 14:47:47 -0700673 }
674 PyErr_Format(PyExc_AttributeError,
675 "module has no attribute '%U'", name);
676 return NULL;
677}
678
Neil Schemenauer10e31cf2001-01-02 15:58:27 +0000679static int
680module_traverse(PyModuleObject *m, visitproc visit, void *arg)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (m->md_def && m->md_def->m_traverse) {
683 int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
684 if (res)
685 return res;
686 }
687 Py_VISIT(m->md_dict);
688 return 0;
Neil Schemenauer10e31cf2001-01-02 15:58:27 +0000689}
690
Martin v. Löwis1a214512008-06-11 05:26:20 +0000691static int
692module_clear(PyModuleObject *m)
693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (m->md_def && m->md_def->m_clear) {
695 int res = m->md_def->m_clear((PyObject*)m);
696 if (res)
697 return res;
698 }
699 Py_CLEAR(m->md_dict);
700 return 0;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000701}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500703static PyObject *
704module_dir(PyObject *self, PyObject *args)
705{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200706 _Py_IDENTIFIER(__dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500707 PyObject *result = NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200708 PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500709
710 if (dict != NULL) {
711 if (PyDict_Check(dict))
712 result = PyDict_Keys(dict);
713 else {
714 const char *name = PyModule_GetName(self);
715 if (name)
716 PyErr_Format(PyExc_TypeError,
717 "%.200s.__dict__ is not a dictionary",
718 name);
719 }
720 }
721
722 Py_XDECREF(dict);
723 return result;
724}
725
726static PyMethodDef module_methods[] = {
727 {"__dir__", module_dir, METH_NOARGS,
Benjamin Petersonc7284122011-05-24 12:46:15 -0500728 PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500729 {0}
730};
731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000732PyDoc_STRVAR(module_doc,
Guido van Rossumed3e09f2002-06-04 06:02:35 +0000733"module(name[, doc])\n\
734\n\
735Create a module object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000736The name must be a string; the optional doc argument can have any type.");
Guido van Rossumed3e09f2002-06-04 06:02:35 +0000737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738PyTypeObject PyModule_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyVarObject_HEAD_INIT(&PyType_Type, 0)
740 "module", /* tp_name */
741 sizeof(PyModuleObject), /* tp_size */
742 0, /* tp_itemsize */
743 (destructor)module_dealloc, /* tp_dealloc */
744 0, /* tp_print */
745 0, /* tp_getattr */
746 0, /* tp_setattr */
747 0, /* tp_reserved */
748 (reprfunc)module_repr, /* tp_repr */
749 0, /* tp_as_number */
750 0, /* tp_as_sequence */
751 0, /* tp_as_mapping */
752 0, /* tp_hash */
753 0, /* tp_call */
754 0, /* tp_str */
Benjamin Peterson1184e262014-04-24 19:29:23 -0400755 (getattrofunc)module_getattro, /* tp_getattro */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject_GenericSetAttr, /* tp_setattro */
757 0, /* tp_as_buffer */
758 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
759 Py_TPFLAGS_BASETYPE, /* tp_flags */
760 module_doc, /* tp_doc */
761 (traverseproc)module_traverse, /* tp_traverse */
762 (inquiry)module_clear, /* tp_clear */
763 0, /* tp_richcompare */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200764 offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 0, /* tp_iter */
766 0, /* tp_iternext */
Benjamin Peterson82b00c12011-05-24 11:09:06 -0500767 module_methods, /* tp_methods */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 module_members, /* tp_members */
769 0, /* tp_getset */
770 0, /* tp_base */
771 0, /* tp_dict */
772 0, /* tp_descr_get */
773 0, /* tp_descr_set */
774 offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
775 (initproc)module_init, /* tp_init */
776 PyType_GenericAlloc, /* tp_alloc */
777 PyType_GenericNew, /* tp_new */
778 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779};