Merged revisions 78818 via svnmerge from
[python/dscho.git] / Objects / moduleobject.c
blobc1dd228abf4cb98209d93e7c9ee345e04adb8e04
2 /* Module object implementation */
4 #include "Python.h"
5 #include "structmember.h"
7 static Py_ssize_t max_module_number;
9 typedef struct {
10 PyObject_HEAD
11 PyObject *md_dict;
12 struct PyModuleDef *md_def;
13 void *md_state;
14 } PyModuleObject;
16 static PyMemberDef module_members[] = {
17 {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
18 {0}
21 static PyTypeObject moduledef_type = {
22 PyVarObject_HEAD_INIT(&PyType_Type, 0)
23 "moduledef", /* tp_name */
24 sizeof(struct PyModuleDef), /* tp_size */
25 0, /* tp_itemsize */
29 PyObject *
30 PyModule_New(const char *name)
32 PyModuleObject *m;
33 PyObject *nameobj;
34 m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
35 if (m == NULL)
36 return NULL;
37 m->md_def = NULL;
38 m->md_state = NULL;
39 nameobj = PyUnicode_FromString(name);
40 m->md_dict = PyDict_New();
41 if (m->md_dict == NULL || nameobj == NULL)
42 goto fail;
43 if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0)
44 goto fail;
45 if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0)
46 goto fail;
47 if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0)
48 goto fail;
49 Py_DECREF(nameobj);
50 PyObject_GC_Track(m);
51 return (PyObject *)m;
53 fail:
54 Py_XDECREF(nameobj);
55 Py_DECREF(m);
56 return NULL;
59 static char api_version_warning[] =
60 "Python C API version mismatch for module %.100s:\
61 This Python has API version %d, module %.100s has version %d.";
63 PyObject *
64 PyModule_Create2(struct PyModuleDef* module, int module_api_version)
66 PyObject *d, *v, *n;
67 PyMethodDef *ml;
68 const char* name;
69 PyModuleObject *m;
70 if (!Py_IsInitialized())
71 Py_FatalError("Interpreter not initialized (version mismatch?)");
72 if (PyType_Ready(&moduledef_type) < 0)
73 return NULL;
74 if (module->m_base.m_index == 0) {
75 max_module_number++;
76 Py_REFCNT(module) = 1;
77 Py_TYPE(module) = &moduledef_type;
78 module->m_base.m_index = max_module_number;
80 name = module->m_name;
81 if (module_api_version != PYTHON_API_VERSION) {
82 char message[512];
83 PyOS_snprintf(message, sizeof(message),
84 api_version_warning, name,
85 PYTHON_API_VERSION, name,
86 module_api_version);
87 if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1))
88 return NULL;
90 /* Make sure name is fully qualified.
92 This is a bit of a hack: when the shared library is loaded,
93 the module name is "package.module", but the module calls
94 PyModule_Create*() with just "module" for the name. The shared
95 library loader squirrels away the true name of the module in
96 _Py_PackageContext, and PyModule_Create*() will substitute this
97 (if the name actually matches).
99 if (_Py_PackageContext != NULL) {
100 char *p = strrchr(_Py_PackageContext, '.');
101 if (p != NULL && strcmp(module->m_name, p+1) == 0) {
102 name = _Py_PackageContext;
103 _Py_PackageContext = NULL;
106 if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
107 return NULL;
109 if (module->m_size > 0) {
110 m->md_state = PyMem_MALLOC(module->m_size);
111 if (!m->md_state) {
112 PyErr_NoMemory();
113 Py_DECREF(m);
114 return NULL;
116 memset(m->md_state, 0, module->m_size);
119 d = PyModule_GetDict((PyObject*)m);
120 if (module->m_methods != NULL) {
121 n = PyUnicode_FromString(name);
122 if (n == NULL)
123 return NULL;
124 for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
125 if ((ml->ml_flags & METH_CLASS) ||
126 (ml->ml_flags & METH_STATIC)) {
127 PyErr_SetString(PyExc_ValueError,
128 "module functions cannot set"
129 " METH_CLASS or METH_STATIC");
130 Py_DECREF(n);
131 return NULL;
133 v = PyCFunction_NewEx(ml, (PyObject*)m, n);
134 if (v == NULL) {
135 Py_DECREF(n);
136 return NULL;
138 if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
139 Py_DECREF(v);
140 Py_DECREF(n);
141 return NULL;
143 Py_DECREF(v);
145 Py_DECREF(n);
147 if (module->m_doc != NULL) {
148 v = PyUnicode_FromString(module->m_doc);
149 if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
150 Py_XDECREF(v);
151 return NULL;
153 Py_DECREF(v);
155 m->md_def = module;
156 return (PyObject*)m;
160 PyObject *
161 PyModule_GetDict(PyObject *m)
163 PyObject *d;
164 if (!PyModule_Check(m)) {
165 PyErr_BadInternalCall();
166 return NULL;
168 d = ((PyModuleObject *)m) -> md_dict;
169 if (d == NULL)
170 ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
171 return d;
174 const char *
175 PyModule_GetName(PyObject *m)
177 PyObject *d;
178 PyObject *nameobj;
179 if (!PyModule_Check(m)) {
180 PyErr_BadArgument();
181 return NULL;
183 d = ((PyModuleObject *)m)->md_dict;
184 if (d == NULL ||
185 (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
186 !PyUnicode_Check(nameobj))
188 PyErr_SetString(PyExc_SystemError, "nameless module");
189 return NULL;
191 return _PyUnicode_AsString(nameobj);
194 const char *
195 PyModule_GetFilename(PyObject *m)
197 PyObject *d;
198 PyObject *fileobj;
199 if (!PyModule_Check(m)) {
200 PyErr_BadArgument();
201 return NULL;
203 d = ((PyModuleObject *)m)->md_dict;
204 if (d == NULL ||
205 (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
206 !PyUnicode_Check(fileobj))
208 PyErr_SetString(PyExc_SystemError, "module filename missing");
209 return NULL;
211 return _PyUnicode_AsString(fileobj);
214 PyModuleDef*
215 PyModule_GetDef(PyObject* m)
217 if (!PyModule_Check(m)) {
218 PyErr_BadArgument();
219 return NULL;
221 return ((PyModuleObject *)m)->md_def;
224 void*
225 PyModule_GetState(PyObject* m)
227 if (!PyModule_Check(m)) {
228 PyErr_BadArgument();
229 return NULL;
231 return ((PyModuleObject *)m)->md_state;
234 void
235 _PyModule_Clear(PyObject *m)
237 /* To make the execution order of destructors for global
238 objects a bit more predictable, we first zap all objects
239 whose name starts with a single underscore, before we clear
240 the entire dictionary. We zap them by replacing them with
241 None, rather than deleting them from the dictionary, to
242 avoid rehashing the dictionary (to some extent). */
244 Py_ssize_t pos;
245 PyObject *key, *value;
246 PyObject *d;
248 d = ((PyModuleObject *)m)->md_dict;
249 if (d == NULL)
250 return;
252 /* First, clear only names starting with a single underscore */
253 pos = 0;
254 while (PyDict_Next(d, &pos, &key, &value)) {
255 if (value != Py_None && PyUnicode_Check(key)) {
256 const char *s = _PyUnicode_AsString(key);
257 if (s[0] == '_' && s[1] != '_') {
258 if (Py_VerboseFlag > 1)
259 PySys_WriteStderr("# clear[1] %s\n", s);
260 PyDict_SetItem(d, key, Py_None);
265 /* Next, clear all names except for __builtins__ */
266 pos = 0;
267 while (PyDict_Next(d, &pos, &key, &value)) {
268 if (value != Py_None && PyUnicode_Check(key)) {
269 const char *s = _PyUnicode_AsString(key);
270 if (s[0] != '_' || strcmp(s, "__builtins__") != 0) {
271 if (Py_VerboseFlag > 1)
272 PySys_WriteStderr("# clear[2] %s\n", s);
273 PyDict_SetItem(d, key, Py_None);
278 /* Note: we leave __builtins__ in place, so that destructors
279 of non-global objects defined in this module can still use
280 builtins, in particularly 'None'. */
284 /* Methods */
286 static int
287 module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
289 static char *kwlist[] = {"name", "doc", NULL};
290 PyObject *dict, *name = Py_None, *doc = Py_None;
291 if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
292 kwlist, &name, &doc))
293 return -1;
294 dict = m->md_dict;
295 if (dict == NULL) {
296 dict = PyDict_New();
297 if (dict == NULL)
298 return -1;
299 m->md_dict = dict;
301 if (PyDict_SetItemString(dict, "__name__", name) < 0)
302 return -1;
303 if (PyDict_SetItemString(dict, "__doc__", doc) < 0)
304 return -1;
305 return 0;
308 static void
309 module_dealloc(PyModuleObject *m)
311 PyObject_GC_UnTrack(m);
312 if (m->md_def && m->md_def->m_free)
313 m->md_def->m_free(m);
314 if (m->md_dict != NULL) {
315 /* If we are the only ones holding a reference, we can clear
316 the dictionary. */
317 if (Py_REFCNT(m->md_dict) == 1)
318 _PyModule_Clear((PyObject *)m);
319 Py_DECREF(m->md_dict);
321 if (m->md_state != NULL)
322 PyMem_FREE(m->md_state);
323 Py_TYPE(m)->tp_free((PyObject *)m);
326 static PyObject *
327 module_repr(PyModuleObject *m)
329 const char *name;
330 const char *filename;
332 name = PyModule_GetName((PyObject *)m);
333 if (name == NULL) {
334 PyErr_Clear();
335 name = "?";
337 filename = PyModule_GetFilename((PyObject *)m);
338 if (filename == NULL) {
339 PyErr_Clear();
340 return PyUnicode_FromFormat("<module '%s' (built-in)>", name);
342 return PyUnicode_FromFormat("<module '%s' from '%s'>", name, filename);
345 static int
346 module_traverse(PyModuleObject *m, visitproc visit, void *arg)
348 if (m->md_def && m->md_def->m_traverse) {
349 int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
350 if (res)
351 return res;
353 Py_VISIT(m->md_dict);
354 return 0;
357 static int
358 module_clear(PyModuleObject *m)
360 if (m->md_def && m->md_def->m_clear) {
361 int res = m->md_def->m_clear((PyObject*)m);
362 if (res)
363 return res;
365 Py_CLEAR(m->md_dict);
366 return 0;
370 PyDoc_STRVAR(module_doc,
371 "module(name[, doc])\n\
373 Create a module object.\n\
374 The name must be a string; the optional doc argument can have any type.");
376 PyTypeObject PyModule_Type = {
377 PyVarObject_HEAD_INIT(&PyType_Type, 0)
378 "module", /* tp_name */
379 sizeof(PyModuleObject), /* tp_size */
380 0, /* tp_itemsize */
381 (destructor)module_dealloc, /* tp_dealloc */
382 0, /* tp_print */
383 0, /* tp_getattr */
384 0, /* tp_setattr */
385 0, /* tp_reserved */
386 (reprfunc)module_repr, /* tp_repr */
387 0, /* tp_as_number */
388 0, /* tp_as_sequence */
389 0, /* tp_as_mapping */
390 0, /* tp_hash */
391 0, /* tp_call */
392 0, /* tp_str */
393 PyObject_GenericGetAttr, /* tp_getattro */
394 PyObject_GenericSetAttr, /* tp_setattro */
395 0, /* tp_as_buffer */
396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
397 Py_TPFLAGS_BASETYPE, /* tp_flags */
398 module_doc, /* tp_doc */
399 (traverseproc)module_traverse, /* tp_traverse */
400 (inquiry)module_clear, /* tp_clear */
401 0, /* tp_richcompare */
402 0, /* tp_weaklistoffset */
403 0, /* tp_iter */
404 0, /* tp_iternext */
405 0, /* tp_methods */
406 module_members, /* tp_members */
407 0, /* tp_getset */
408 0, /* tp_base */
409 0, /* tp_dict */
410 0, /* tp_descr_get */
411 0, /* tp_descr_set */
412 offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
413 (initproc)module_init, /* tp_init */
414 PyType_GenericAlloc, /* tp_alloc */
415 PyType_GenericNew, /* tp_new */
416 PyObject_GC_Del, /* tp_free */