2
/* Module object implementation */
5
#include "structmember.h"
7
static Py_ssize_t max_module_number;
12
struct PyModuleDef *md_def;
14
PyObject *md_weaklist;
15
PyObject *md_name; /* for logging purposes after md_dict is cleared */
18
static PyMemberDef module_members[] = {
19
{"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
23
static PyTypeObject moduledef_type = {
24
PyVarObject_HEAD_INIT(&PyType_Type, 0)
25
"moduledef", /* tp_name */
26
sizeof(struct PyModuleDef), /* tp_size */
32
module_init_dict(PyModuleObject *mod, PyObject *md_dict,
33
PyObject *name, PyObject *doc)
40
if (PyDict_SetItemString(md_dict, "__name__", name) != 0)
42
if (PyDict_SetItemString(md_dict, "__doc__", doc) != 0)
44
if (PyDict_SetItemString(md_dict, "__package__", Py_None) != 0)
46
if (PyDict_SetItemString(md_dict, "__loader__", Py_None) != 0)
48
if (PyDict_SetItemString(md_dict, "__spec__", Py_None) != 0)
50
if (PyUnicode_CheckExact(name)) {
52
Py_XDECREF(mod->md_name);
61
PyModule_NewObject(PyObject *name)
64
m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
69
m->md_weaklist = NULL;
71
m->md_dict = PyDict_New();
72
if (module_init_dict(m, m->md_dict, name, NULL) != 0)
83
PyModule_New(const char *name)
85
PyObject *nameobj, *module;
86
nameobj = PyUnicode_FromString(name);
89
module = PyModule_NewObject(nameobj);
96
PyModule_Create2(struct PyModuleDef* module, int module_api_version)
102
PyInterpreterState *interp = PyThreadState_Get()->interp;
103
if (interp->modules == NULL)
104
Py_FatalError("Python import machinery not initialized");
105
if (PyType_Ready(&moduledef_type) < 0)
107
if (module->m_base.m_index == 0) {
109
Py_REFCNT(module) = 1;
110
Py_TYPE(module) = &moduledef_type;
111
module->m_base.m_index = max_module_number;
113
name = module->m_name;
114
if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
116
err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
117
"Python C API version mismatch for module %.100s: "
118
"This Python has API version %d, module %.100s has version %d.",
120
PYTHON_API_VERSION, name, module_api_version);
124
/* Make sure name is fully qualified.
126
This is a bit of a hack: when the shared library is loaded,
127
the module name is "package.module", but the module calls
128
PyModule_Create*() with just "module" for the name. The shared
129
library loader squirrels away the true name of the module in
130
_Py_PackageContext, and PyModule_Create*() will substitute this
131
(if the name actually matches).
133
if (_Py_PackageContext != NULL) {
134
char *p = strrchr(_Py_PackageContext, '.');
135
if (p != NULL && strcmp(module->m_name, p+1) == 0) {
136
name = _Py_PackageContext;
137
_Py_PackageContext = NULL;
140
if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
143
if (module->m_size > 0) {
144
m->md_state = PyMem_MALLOC(module->m_size);
150
memset(m->md_state, 0, module->m_size);
153
d = PyModule_GetDict((PyObject*)m);
154
if (module->m_methods != NULL) {
155
n = PyUnicode_FromString(name);
160
for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
161
if ((ml->ml_flags & METH_CLASS) ||
162
(ml->ml_flags & METH_STATIC)) {
163
PyErr_SetString(PyExc_ValueError,
164
"module functions cannot set"
165
" METH_CLASS or METH_STATIC");
170
v = PyCFunction_NewEx(ml, (PyObject*)m, n);
176
if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
186
if (module->m_doc != NULL) {
187
v = PyUnicode_FromString(module->m_doc);
188
if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
201
PyModule_GetDict(PyObject *m)
204
if (!PyModule_Check(m)) {
205
PyErr_BadInternalCall();
208
d = ((PyModuleObject *)m) -> md_dict;
210
((PyModuleObject *)m) -> md_dict = d = PyDict_New();
215
PyModule_GetNameObject(PyObject *m)
219
if (!PyModule_Check(m)) {
223
d = ((PyModuleObject *)m)->md_dict;
225
(name = PyDict_GetItemString(d, "__name__")) == NULL ||
226
!PyUnicode_Check(name))
228
PyErr_SetString(PyExc_SystemError, "nameless module");
236
PyModule_GetName(PyObject *m)
238
PyObject *name = PyModule_GetNameObject(m);
241
Py_DECREF(name); /* module dict has still a reference */
242
return _PyUnicode_AsString(name);
246
PyModule_GetFilenameObject(PyObject *m)
250
if (!PyModule_Check(m)) {
254
d = ((PyModuleObject *)m)->md_dict;
256
(fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
257
!PyUnicode_Check(fileobj))
259
PyErr_SetString(PyExc_SystemError, "module filename missing");
267
PyModule_GetFilename(PyObject *m)
271
fileobj = PyModule_GetFilenameObject(m);
274
utf8 = _PyUnicode_AsString(fileobj);
275
Py_DECREF(fileobj); /* module dict has still a reference */
280
PyModule_GetDef(PyObject* m)
282
if (!PyModule_Check(m)) {
286
return ((PyModuleObject *)m)->md_def;
290
PyModule_GetState(PyObject* m)
292
if (!PyModule_Check(m)) {
296
return ((PyModuleObject *)m)->md_state;
300
_PyModule_Clear(PyObject *m)
302
/* To make the execution order of destructors for global
303
objects a bit more predictable, we first zap all objects
304
whose name starts with a single underscore, before we clear
305
the entire dictionary. We zap them by replacing them with
306
None, rather than deleting them from the dictionary, to
307
avoid rehashing the dictionary (to some extent). */
310
PyObject *key, *value;
313
d = ((PyModuleObject *)m)->md_dict;
317
/* First, clear only names starting with a single underscore */
319
while (PyDict_Next(d, &pos, &key, &value)) {
320
if (value != Py_None && PyUnicode_Check(key)) {
321
if (PyUnicode_READ_CHAR(key, 0) == '_' &&
322
PyUnicode_READ_CHAR(key, 1) != '_') {
323
if (Py_VerboseFlag > 1) {
324
const char *s = _PyUnicode_AsString(key);
326
PySys_WriteStderr("# clear[1] %s\n", s);
330
PyDict_SetItem(d, key, Py_None);
335
/* Next, clear all names except for __builtins__ */
337
while (PyDict_Next(d, &pos, &key, &value)) {
338
if (value != Py_None && PyUnicode_Check(key)) {
339
if (PyUnicode_READ_CHAR(key, 0) != '_' ||
340
PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
342
if (Py_VerboseFlag > 1) {
343
const char *s = _PyUnicode_AsString(key);
345
PySys_WriteStderr("# clear[2] %s\n", s);
349
PyDict_SetItem(d, key, Py_None);
354
/* Note: we leave __builtins__ in place, so that destructors
355
of non-global objects defined in this module can still use
356
builtins, in particularly 'None'. */
363
module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
365
static char *kwlist[] = {"name", "doc", NULL};
366
PyObject *dict, *name = Py_None, *doc = Py_None;
367
if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
368
kwlist, &name, &doc))
377
if (module_init_dict(m, dict, name, doc) < 0)
383
module_dealloc(PyModuleObject *m)
385
PyObject_GC_UnTrack(m);
386
if (Py_VerboseFlag && m->md_name) {
387
PySys_FormatStderr("# destroy %S\n", m->md_name);
389
if (m->md_weaklist != NULL)
390
PyObject_ClearWeakRefs((PyObject *) m);
391
if (m->md_def && m->md_def->m_free)
392
m->md_def->m_free(m);
393
Py_XDECREF(m->md_dict);
394
Py_XDECREF(m->md_name);
395
if (m->md_state != NULL)
396
PyMem_FREE(m->md_state);
397
Py_TYPE(m)->tp_free((PyObject *)m);
401
module_repr(PyModuleObject *m)
403
PyThreadState *tstate = PyThreadState_GET();
404
PyInterpreterState *interp = tstate->interp;
406
return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m);
410
module_traverse(PyModuleObject *m, visitproc visit, void *arg)
412
if (m->md_def && m->md_def->m_traverse) {
413
int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
417
Py_VISIT(m->md_dict);
422
module_clear(PyModuleObject *m)
424
if (m->md_def && m->md_def->m_clear) {
425
int res = m->md_def->m_clear((PyObject*)m);
429
Py_CLEAR(m->md_dict);
434
module_dir(PyObject *self, PyObject *args)
436
_Py_IDENTIFIER(__dict__);
437
PyObject *result = NULL;
438
PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);
441
if (PyDict_Check(dict))
442
result = PyDict_Keys(dict);
444
const char *name = PyModule_GetName(self);
446
PyErr_Format(PyExc_TypeError,
447
"%.200s.__dict__ is not a dictionary",
456
static PyMethodDef module_methods[] = {
457
{"__dir__", module_dir, METH_NOARGS,
458
PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")},
463
PyDoc_STRVAR(module_doc,
464
"module(name[, doc])\n\
466
Create a module object.\n\
467
The name must be a string; the optional doc argument can have any type.");
469
PyTypeObject PyModule_Type = {
470
PyVarObject_HEAD_INIT(&PyType_Type, 0)
471
"module", /* tp_name */
472
sizeof(PyModuleObject), /* tp_size */
474
(destructor)module_dealloc, /* tp_dealloc */
479
(reprfunc)module_repr, /* tp_repr */
480
0, /* tp_as_number */
481
0, /* tp_as_sequence */
482
0, /* tp_as_mapping */
486
PyObject_GenericGetAttr, /* tp_getattro */
487
PyObject_GenericSetAttr, /* tp_setattro */
488
0, /* tp_as_buffer */
489
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
490
Py_TPFLAGS_BASETYPE, /* tp_flags */
491
module_doc, /* tp_doc */
492
(traverseproc)module_traverse, /* tp_traverse */
493
(inquiry)module_clear, /* tp_clear */
494
0, /* tp_richcompare */
495
offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */
498
module_methods, /* tp_methods */
499
module_members, /* tp_members */
503
0, /* tp_descr_get */
504
0, /* tp_descr_set */
505
offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
506
(initproc)module_init, /* tp_init */
507
PyType_GenericAlloc, /* tp_alloc */
508
PyType_GenericNew, /* tp_new */
509
PyObject_GC_Del, /* tp_free */