2 /* Module definition and import implementation */
6 #include "Python-ast.h"
24 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
27 /* Magic word to reject .pyc files generated by other Python versions.
28 It should change for each incompatible change to the bytecode.
30 The value of CR and LF is incorporated so if you ever read or write
31 a .pyc file in text mode the magic number will be wrong; also, the
32 Apple MPW compiler swaps their values, botching string constants.
34 The magic numbers must be spaced apart atleast 2 values, as the
35 -U interpeter flag will cause MAGIC+1 being used. They have been
36 odd numbers for some time now.
38 There were a variety of old schemes for setting the magic number.
39 The current working scheme is to increment the previous value by
55 Python 2.3a0: 62011 (!)
60 Python 2.5a0: 62081 (ast-branch)
61 Python 2.5a0: 62091 (with)
62 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
65 #define MAGIC (62092 | ((long)'\r'<<16) | ((long)'\n'<<24))
67 /* Magic word as global; note that _PyImport_Init() can change the
68 value of this global to accommodate for alterations of how the
69 compiler works which are enabled by command line switches. */
70 static long pyc_magic
= MAGIC
;
72 /* See _PyImport_FixupExtension() below */
73 static PyObject
*extensions
= NULL
;
75 /* This table is defined in config.c: */
76 extern struct _inittab _PyImport_Inittab
[];
78 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
80 /* these tables define the module suffixes that Python recognizes */
81 struct filedescr
* _PyImport_Filetab
= NULL
;
84 static const struct filedescr _PyImport_StandardFiletab
[] = {
85 {"/py", "U", PY_SOURCE
},
86 {"/pyc", "rb", PY_COMPILED
},
90 static const struct filedescr _PyImport_StandardFiletab
[] = {
91 {".py", "U", PY_SOURCE
},
93 {".pyw", "U", PY_SOURCE
},
95 {".pyc", "rb", PY_COMPILED
},
100 /* Initialize things */
105 const struct filedescr
*scan
;
106 struct filedescr
*filetab
;
110 /* prepare _PyImport_Filetab: copy entries from
111 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
113 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
115 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
117 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
118 memcpy(filetab
, _PyImport_DynLoadFiletab
,
119 countD
* sizeof(struct filedescr
));
120 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
121 countS
* sizeof(struct filedescr
));
122 filetab
[countD
+ countS
].suffix
= NULL
;
124 _PyImport_Filetab
= filetab
;
126 if (Py_OptimizeFlag
) {
127 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
128 for (; filetab
->suffix
!= NULL
; filetab
++) {
130 if (strcmp(filetab
->suffix
, ".pyc") == 0)
131 filetab
->suffix
= ".pyo";
133 if (strcmp(filetab
->suffix
, "/pyc") == 0)
134 filetab
->suffix
= "/pyo";
139 if (Py_UnicodeFlag
) {
140 /* Fix the pyc_magic so that byte compiled code created
141 using the all-Unicode method doesn't interfere with
142 code created in normal operation mode. */
143 pyc_magic
= MAGIC
+ 1;
148 _PyImportHooks_Init(void)
150 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
153 /* adding sys.path_hooks and sys.path_importer_cache, setting up
157 PySys_WriteStderr("# installing zipimport hook\n");
162 err
= PySys_SetObject("meta_path", v
);
169 err
= PySys_SetObject("path_importer_cache", v
);
173 path_hooks
= PyList_New(0);
174 if (path_hooks
== NULL
)
176 err
= PySys_SetObject("path_hooks", path_hooks
);
180 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
181 "path_importer_cache failed");
183 zimpimport
= PyImport_ImportModule("zipimport");
184 if (zimpimport
== NULL
) {
185 PyErr_Clear(); /* No zip import module -- okay */
187 PySys_WriteStderr("# can't import zipimport\n");
190 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
192 Py_DECREF(zimpimport
);
193 if (zipimporter
== NULL
) {
194 PyErr_Clear(); /* No zipimporter object -- okay */
197 "# can't import zipimport.zipimporter\n");
200 /* sys.path_hooks.append(zipimporter) */
201 err
= PyList_Append(path_hooks
, zipimporter
);
202 Py_DECREF(zipimporter
);
207 "# installed zipimport hook\n");
210 Py_DECREF(path_hooks
);
216 Py_XDECREF(extensions
);
218 PyMem_DEL(_PyImport_Filetab
);
219 _PyImport_Filetab
= NULL
;
223 /* Locking primitives to prevent parallel imports of the same module
224 in different threads to return with a partially loaded module.
225 These calls are serialized by the global interpreter lock. */
229 #include "pythread.h"
231 static PyThread_type_lock import_lock
= 0;
232 static long import_lock_thread
= -1;
233 static int import_lock_level
= 0;
238 long me
= PyThread_get_thread_ident();
240 return; /* Too bad */
241 if (import_lock
== NULL
)
242 import_lock
= PyThread_allocate_lock();
243 if (import_lock_thread
== me
) {
247 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
249 PyThreadState
*tstate
= PyEval_SaveThread();
250 PyThread_acquire_lock(import_lock
, 1);
251 PyEval_RestoreThread(tstate
);
253 import_lock_thread
= me
;
254 import_lock_level
= 1;
260 long me
= PyThread_get_thread_ident();
262 return 0; /* Too bad */
263 if (import_lock_thread
!= me
)
266 if (import_lock_level
== 0) {
267 import_lock_thread
= -1;
268 PyThread_release_lock(import_lock
);
273 /* This function is called from PyOS_AfterFork to ensure that newly
274 created child processes do not share locks with the parent. */
277 _PyImport_ReInitLock(void)
280 if (import_lock
!= NULL
)
281 import_lock
= PyThread_allocate_lock();
287 #define lock_import()
288 #define unlock_import() 0
293 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
296 return PyBool_FromLong(import_lock_thread
!= -1);
298 return PyBool_FromLong(0);
303 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
313 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
316 if (unlock_import() < 0) {
317 PyErr_SetString(PyExc_RuntimeError
,
318 "not holding the import lock");
329 PyImport_GetModuleDict(void)
331 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
332 if (interp
->modules
== NULL
)
333 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
334 return interp
->modules
;
338 /* List of names to clear in sys */
339 static char* sys_deletes
[] = {
340 "path", "argv", "ps1", "ps2", "exitfunc",
341 "exc_type", "exc_value", "exc_traceback",
342 "last_type", "last_value", "last_traceback",
343 "path_hooks", "path_importer_cache", "meta_path",
347 static char* sys_files
[] = {
348 "stdin", "__stdin__",
349 "stdout", "__stdout__",
350 "stderr", "__stderr__",
355 /* Un-initialize things, as good as we can */
358 PyImport_Cleanup(void)
360 Py_ssize_t pos
, ndone
;
362 PyObject
*key
, *value
, *dict
;
363 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
364 PyObject
*modules
= interp
->modules
;
367 return; /* Already done */
369 /* Delete some special variables first. These are common
370 places where user values hide and people complain when their
371 destructors fail. Since the modules containing them are
372 deleted *last* of all, they would come too late in the normal
373 destruction order. Sigh. */
375 value
= PyDict_GetItemString(modules
, "__builtin__");
376 if (value
!= NULL
&& PyModule_Check(value
)) {
377 dict
= PyModule_GetDict(value
);
379 PySys_WriteStderr("# clear __builtin__._\n");
380 PyDict_SetItemString(dict
, "_", Py_None
);
382 value
= PyDict_GetItemString(modules
, "sys");
383 if (value
!= NULL
&& PyModule_Check(value
)) {
386 dict
= PyModule_GetDict(value
);
387 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
389 PySys_WriteStderr("# clear sys.%s\n", *p
);
390 PyDict_SetItemString(dict
, *p
, Py_None
);
392 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
394 PySys_WriteStderr("# restore sys.%s\n", *p
);
395 v
= PyDict_GetItemString(dict
, *(p
+1));
398 PyDict_SetItemString(dict
, *p
, v
);
402 /* First, delete __main__ */
403 value
= PyDict_GetItemString(modules
, "__main__");
404 if (value
!= NULL
&& PyModule_Check(value
)) {
406 PySys_WriteStderr("# cleanup __main__\n");
407 _PyModule_Clear(value
);
408 PyDict_SetItemString(modules
, "__main__", Py_None
);
411 /* The special treatment of __builtin__ here is because even
412 when it's not referenced as a module, its dictionary is
413 referenced by almost every module's __builtins__. Since
414 deleting a module clears its dictionary (even if there are
415 references left to it), we need to delete the __builtin__
416 module last. Likewise, we don't delete sys until the very
417 end because it is implicitly referenced (e.g. by print).
419 Also note that we 'delete' modules by replacing their entry
420 in the modules dict with None, rather than really deleting
421 them; this avoids a rehash of the modules dictionary and
422 also marks them as "non existent" so they won't be
425 /* Next, repeatedly delete modules with a reference count of
426 one (skipping __builtin__ and sys) and delete them */
430 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
431 if (value
->ob_refcnt
!= 1)
433 if (PyString_Check(key
) && PyModule_Check(value
)) {
434 name
= PyString_AS_STRING(key
);
435 if (strcmp(name
, "__builtin__") == 0)
437 if (strcmp(name
, "sys") == 0)
441 "# cleanup[1] %s\n", name
);
442 _PyModule_Clear(value
);
443 PyDict_SetItem(modules
, key
, Py_None
);
449 /* Next, delete all modules (still skipping __builtin__ and sys) */
451 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
452 if (PyString_Check(key
) && PyModule_Check(value
)) {
453 name
= PyString_AS_STRING(key
);
454 if (strcmp(name
, "__builtin__") == 0)
456 if (strcmp(name
, "sys") == 0)
459 PySys_WriteStderr("# cleanup[2] %s\n", name
);
460 _PyModule_Clear(value
);
461 PyDict_SetItem(modules
, key
, Py_None
);
465 /* Next, delete sys and __builtin__ (in that order) */
466 value
= PyDict_GetItemString(modules
, "sys");
467 if (value
!= NULL
&& PyModule_Check(value
)) {
469 PySys_WriteStderr("# cleanup sys\n");
470 _PyModule_Clear(value
);
471 PyDict_SetItemString(modules
, "sys", Py_None
);
473 value
= PyDict_GetItemString(modules
, "__builtin__");
474 if (value
!= NULL
&& PyModule_Check(value
)) {
476 PySys_WriteStderr("# cleanup __builtin__\n");
477 _PyModule_Clear(value
);
478 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
481 /* Finally, clear and delete the modules directory */
482 PyDict_Clear(modules
);
483 interp
->modules
= NULL
;
488 /* Helper for pythonrun.c -- return magic number */
491 PyImport_GetMagicNumber(void)
497 /* Magic for extension modules (built-in as well as dynamically
498 loaded). To prevent initializing an extension module more than
499 once, we keep a static dictionary 'extensions' keyed by module name
500 (for built-in modules) or by filename (for dynamically loaded
501 modules), containing these modules. A copy of the module's
502 dictionary is stored by calling _PyImport_FixupExtension()
503 immediately after the module initialization function succeeds. A
504 copy can be retrieved from there by calling
505 _PyImport_FindExtension(). */
508 _PyImport_FixupExtension(char *name
, char *filename
)
510 PyObject
*modules
, *mod
, *dict
, *copy
;
511 if (extensions
== NULL
) {
512 extensions
= PyDict_New();
513 if (extensions
== NULL
)
516 modules
= PyImport_GetModuleDict();
517 mod
= PyDict_GetItemString(modules
, name
);
518 if (mod
== NULL
|| !PyModule_Check(mod
)) {
519 PyErr_Format(PyExc_SystemError
,
520 "_PyImport_FixupExtension: module %.200s not loaded", name
);
523 dict
= PyModule_GetDict(mod
);
526 copy
= PyDict_Copy(dict
);
529 PyDict_SetItemString(extensions
, filename
, copy
);
535 _PyImport_FindExtension(char *name
, char *filename
)
537 PyObject
*dict
, *mod
, *mdict
;
538 if (extensions
== NULL
)
540 dict
= PyDict_GetItemString(extensions
, filename
);
543 mod
= PyImport_AddModule(name
);
546 mdict
= PyModule_GetDict(mod
);
549 if (PyDict_Update(mdict
, dict
))
552 PySys_WriteStderr("import %s # previously loaded (%s)\n",
558 /* Get the module object corresponding to a module name.
559 First check the modules dictionary if there's one there,
560 if not, create a new one and insert it in the modules dictionary.
561 Because the former action is most common, THIS DOES NOT RETURN A
565 PyImport_AddModule(const char *name
)
567 PyObject
*modules
= PyImport_GetModuleDict();
570 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
573 m
= PyModule_New(name
);
576 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
580 Py_DECREF(m
); /* Yes, it still exists, in modules! */
585 /* Remove name from sys.modules, if it's there. */
587 _RemoveModule(const char *name
)
589 PyObject
*modules
= PyImport_GetModuleDict();
590 if (PyDict_GetItemString(modules
, name
) == NULL
)
592 if (PyDict_DelItemString(modules
, name
) < 0)
593 Py_FatalError("import: deleting existing key in"
594 "sys.modules failed");
597 /* Execute a code object in a module and return the module object
598 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
599 * removed from sys.modules, to avoid leaving damaged module objects
600 * in sys.modules. The caller may wish to restore the original
601 * module object (if any) in this case; PyImport_ReloadModule is an
605 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
607 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
611 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
613 PyObject
*modules
= PyImport_GetModuleDict();
616 m
= PyImport_AddModule(name
);
619 /* If the module is being reloaded, we get the old module back
620 and re-use its dict to exec the new code. */
621 d
= PyModule_GetDict(m
);
622 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
623 if (PyDict_SetItemString(d
, "__builtins__",
624 PyEval_GetBuiltins()) != 0)
627 /* Remember the filename as the __file__ attribute */
629 if (pathname
!= NULL
) {
630 v
= PyString_FromString(pathname
);
635 v
= ((PyCodeObject
*)co
)->co_filename
;
638 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
639 PyErr_Clear(); /* Not important enough to report */
642 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
647 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
648 PyErr_Format(PyExc_ImportError
,
649 "Loaded module %.200s not found in sys.modules",
664 /* Given a pathname for a Python source file, fill a buffer with the
665 pathname for the corresponding compiled file. Return the pathname
666 for the compiled file, or NULL if there's no space in the buffer.
667 Doesn't set an exception. */
670 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
672 size_t len
= strlen(pathname
);
677 /* Treat .pyw as if it were .py. The case of ".pyw" must match
678 that used in _PyImport_StandardFiletab. */
679 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
680 --len
; /* pretend 'w' isn't there */
682 memcpy(buf
, pathname
, len
);
683 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
690 /* Given a pathname for a Python source file, its time of last
691 modification, and a pathname for a compiled file, check whether the
692 compiled file represents the same version of the source. If so,
693 return a FILE pointer for the compiled file, positioned just after
694 the header; if not, return NULL.
695 Doesn't set an exception. */
698 check_compiled_module(char *pathname
, time_t mtime
, char *cpathname
)
704 fp
= fopen(cpathname
, "rb");
707 magic
= PyMarshal_ReadLongFromFile(fp
);
708 if (magic
!= pyc_magic
) {
710 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
714 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
715 if (pyc_mtime
!= mtime
) {
717 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
722 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
727 /* Read a code object from a file and check it for validity */
729 static PyCodeObject
*
730 read_compiled_module(char *cpathname
, FILE *fp
)
734 co
= PyMarshal_ReadLastObjectFromFile(fp
);
737 if (!PyCode_Check(co
)) {
738 PyErr_Format(PyExc_ImportError
,
739 "Non-code object in %.200s", cpathname
);
743 return (PyCodeObject
*)co
;
747 /* Load a module from a compiled file, execute it, and return its
748 module object WITH INCREMENTED REFERENCE COUNT */
751 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
757 magic
= PyMarshal_ReadLongFromFile(fp
);
758 if (magic
!= pyc_magic
) {
759 PyErr_Format(PyExc_ImportError
,
760 "Bad magic number in %.200s", cpathname
);
763 (void) PyMarshal_ReadLongFromFile(fp
);
764 co
= read_compiled_module(cpathname
, fp
);
768 PySys_WriteStderr("import %s # precompiled from %s\n",
770 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
776 /* Parse a source file and return the corresponding code object */
778 static PyCodeObject
*
779 parse_source_module(const char *pathname
, FILE *fp
)
781 PyCodeObject
*co
= NULL
;
783 PyArena
*arena
= PyArena_New();
785 mod
= PyParser_ASTFromFile(fp
, pathname
, Py_file_input
, 0, 0, 0,
788 co
= PyAST_Compile(mod
, pathname
, NULL
, arena
);
795 /* Helper to open a bytecode file for writing in exclusive mode */
798 open_exclusive(char *filename
)
800 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
801 /* Use O_EXCL to avoid a race condition when another process tries to
802 write the same file. When that happens, our open() call fails,
803 which is just fine (since it's only a cache).
804 XXX If the file exists and is writable but the directory is not
805 writable, the file will never be written. Oh well.
808 (void) unlink(filename
);
809 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
811 |O_BINARY
/* necessary for Windows */
814 , 0666, "ctxt=bin", "shr=nil"
821 return fdopen(fd
, "wb");
823 /* Best we can do -- on Windows this can't happen anyway */
824 return fopen(filename
, "wb");
829 /* Write a compiled module to a file, placing the time of last
830 modification of its source into the header.
831 Errors are ignored, if a write error occurs an attempt is made to
835 write_compiled_module(PyCodeObject
*co
, char *cpathname
, time_t mtime
)
839 fp
= open_exclusive(cpathname
);
843 "# can't create %s\n", cpathname
);
846 PyMarshal_WriteLongToFile(pyc_magic
, fp
, Py_MARSHAL_VERSION
);
847 /* First write a 0 for mtime */
848 PyMarshal_WriteLongToFile(0L, fp
, Py_MARSHAL_VERSION
);
849 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
, Py_MARSHAL_VERSION
);
850 if (fflush(fp
) != 0 || ferror(fp
)) {
852 PySys_WriteStderr("# can't write %s\n", cpathname
);
853 /* Don't keep partial file */
855 (void) unlink(cpathname
);
858 /* Now write the true mtime */
860 assert(mtime
< LONG_MAX
);
861 PyMarshal_WriteLongToFile((long)mtime
, fp
, Py_MARSHAL_VERSION
);
865 PySys_WriteStderr("# wrote %s\n", cpathname
);
869 /* Load a source module from a given file and return its module
870 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
871 byte-compiled file, use that instead. */
874 load_source_module(char *name
, char *pathname
, FILE *fp
)
878 char buf
[MAXPATHLEN
+1];
883 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
884 if (mtime
== (time_t)(-1)) {
885 PyErr_Format(PyExc_RuntimeError
,
886 "unable to get modification time from '%s'",
890 #if SIZEOF_TIME_T > 4
891 /* Python's .pyc timestamp handling presumes that the timestamp fits
892 in 4 bytes. This will be fine until sometime in the year 2038,
893 when a 4-byte signed time_t will overflow.
896 PyErr_SetString(PyExc_OverflowError
,
897 "modification time overflows a 4 byte field");
901 cpathname
= make_compiled_pathname(pathname
, buf
,
902 (size_t)MAXPATHLEN
+ 1);
903 if (cpathname
!= NULL
&&
904 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
905 co
= read_compiled_module(cpathname
, fpc
);
910 PySys_WriteStderr("import %s # precompiled from %s\n",
912 pathname
= cpathname
;
915 co
= parse_source_module(pathname
, fp
);
919 PySys_WriteStderr("import %s # from %s\n",
921 write_compiled_module(co
, cpathname
, mtime
);
923 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
931 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
932 static struct filedescr
*find_module(char *, char *, PyObject
*,
933 char *, size_t, FILE **, PyObject
**);
934 static struct _frozen
*find_frozen(char *name
);
936 /* Load a package and return its module object WITH INCREMENTED
940 load_package(char *name
, char *pathname
)
943 PyObject
*file
= NULL
;
944 PyObject
*path
= NULL
;
946 char buf
[MAXPATHLEN
+1];
948 struct filedescr
*fdp
;
950 m
= PyImport_AddModule(name
);
954 PySys_WriteStderr("import %s # directory %s\n",
956 d
= PyModule_GetDict(m
);
957 file
= PyString_FromString(pathname
);
960 path
= Py_BuildValue("[O]", file
);
963 err
= PyDict_SetItemString(d
, "__file__", file
);
965 err
= PyDict_SetItemString(d
, "__path__", path
);
969 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
971 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
979 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
993 /* Helper to test for built-in module */
996 is_builtin(char *name
)
999 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
1000 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
1001 if (PyImport_Inittab
[i
].initfunc
== NULL
)
1011 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1012 possibly by fetching it from the path_importer_cache dict. If it
1013 wasn't yet cached, traverse path_hooks until it a hook is found
1014 that can handle the path item. Return None if no hook could;
1015 this tells our caller it should fall back to the builtin
1016 import mechanism. Cache the result in path_importer_cache.
1017 Returns a borrowed reference. */
1020 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
1024 Py_ssize_t j
, nhooks
;
1026 /* These conditions are the caller's responsibility: */
1027 assert(PyList_Check(path_hooks
));
1028 assert(PyDict_Check(path_importer_cache
));
1030 nhooks
= PyList_Size(path_hooks
);
1032 return NULL
; /* Shouldn't happen */
1034 importer
= PyDict_GetItem(path_importer_cache
, p
);
1035 if (importer
!= NULL
)
1038 /* set path_importer_cache[p] to None to avoid recursion */
1039 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1042 for (j
= 0; j
< nhooks
; j
++) {
1043 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1046 importer
= PyObject_CallFunctionObjArgs(hook
, p
, NULL
);
1047 if (importer
!= NULL
)
1050 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1055 if (importer
== NULL
)
1057 else if (importer
!= Py_None
) {
1058 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1059 Py_DECREF(importer
);
1066 /* Search the path (default sys.path) for a module. Return the
1067 corresponding filedescr struct, and (via return arguments) the
1068 pathname and an open file. Return NULL if the module is not found. */
1071 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1072 char *, Py_ssize_t
);
1075 static int case_ok(char *, Py_ssize_t
, Py_ssize_t
, char *);
1076 static int find_init_module(char *); /* Forward */
1077 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1079 static struct filedescr
*
1080 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1081 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1083 Py_ssize_t i
, npath
;
1084 size_t len
, namelen
;
1085 struct filedescr
*fdp
= NULL
;
1088 PyObject
*path_hooks
, *path_importer_cache
;
1090 struct stat statbuf
;
1092 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1093 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1094 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1095 char name
[MAXPATHLEN
+1];
1096 #if defined(PYOS_OS2)
1098 size_t saved_namelen
;
1099 char *saved_buf
= NULL
;
1101 if (p_loader
!= NULL
)
1104 if (strlen(subname
) > MAXPATHLEN
) {
1105 PyErr_SetString(PyExc_OverflowError
,
1106 "module name is too long");
1109 strcpy(name
, subname
);
1111 /* sys.meta_path import hook */
1112 if (p_loader
!= NULL
) {
1113 PyObject
*meta_path
;
1115 meta_path
= PySys_GetObject("meta_path");
1116 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1117 PyErr_SetString(PyExc_ImportError
,
1118 "sys.meta_path must be a list of "
1122 Py_INCREF(meta_path
); /* zap guard */
1123 npath
= PyList_Size(meta_path
);
1124 for (i
= 0; i
< npath
; i
++) {
1126 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1127 loader
= PyObject_CallMethod(hook
, "find_module",
1131 if (loader
== NULL
) {
1132 Py_DECREF(meta_path
);
1133 return NULL
; /* true error */
1135 if (loader
!= Py_None
) {
1136 /* a loader was found */
1138 Py_DECREF(meta_path
);
1139 return &importhookdescr
;
1143 Py_DECREF(meta_path
);
1146 if (path
!= NULL
&& PyString_Check(path
)) {
1147 /* The only type of submodule allowed inside a "frozen"
1148 package are other frozen modules or packages. */
1149 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1150 PyErr_SetString(PyExc_ImportError
,
1151 "full frozen module name too long");
1154 strcpy(buf
, PyString_AsString(path
));
1158 if (find_frozen(name
) != NULL
) {
1162 PyErr_Format(PyExc_ImportError
,
1163 "No frozen submodule named %.200s", name
);
1167 if (is_builtin(name
)) {
1171 if ((find_frozen(name
)) != NULL
) {
1177 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1183 path
= PySys_GetObject("path");
1185 if (path
== NULL
|| !PyList_Check(path
)) {
1186 PyErr_SetString(PyExc_ImportError
,
1187 "sys.path must be a list of directory names");
1191 path_hooks
= PySys_GetObject("path_hooks");
1192 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1193 PyErr_SetString(PyExc_ImportError
,
1194 "sys.path_hooks must be a list of "
1198 path_importer_cache
= PySys_GetObject("path_importer_cache");
1199 if (path_importer_cache
== NULL
||
1200 !PyDict_Check(path_importer_cache
)) {
1201 PyErr_SetString(PyExc_ImportError
,
1202 "sys.path_importer_cache must be a dict");
1206 npath
= PyList_Size(path
);
1207 namelen
= strlen(name
);
1208 for (i
= 0; i
< npath
; i
++) {
1209 PyObject
*copy
= NULL
;
1210 PyObject
*v
= PyList_GetItem(path
, i
);
1211 #ifdef Py_USING_UNICODE
1212 if (PyUnicode_Check(v
)) {
1213 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1214 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1221 if (!PyString_Check(v
))
1223 len
= PyString_GET_SIZE(v
);
1224 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1226 continue; /* Too long */
1228 strcpy(buf
, PyString_AS_STRING(v
));
1229 if (strlen(buf
) != len
) {
1231 continue; /* v contains '\0' */
1234 /* sys.path_hooks import hook */
1235 if (p_loader
!= NULL
) {
1238 importer
= get_path_importer(path_importer_cache
,
1240 if (importer
== NULL
)
1242 /* Note: importer is a borrowed reference */
1243 if (importer
== Py_False
) {
1244 /* Cached as not being a valid dir. */
1248 else if (importer
== Py_True
) {
1249 /* Cached as being a valid dir, so just
1250 * continue below. */
1252 else if (importer
== Py_None
) {
1253 /* No importer was found, so it has to be a file.
1254 * Check if the directory is valid.
1255 * Note that the empty string is a valid path, but
1256 * not stat'able, hence the check for len. */
1258 if (len
&& stat(buf
, &statbuf
) != 0) {
1259 /* Directory does not exist. */
1260 PyDict_SetItem(path_importer_cache
,
1265 PyDict_SetItem(path_importer_cache
,
1271 /* A real import hook importer was found. */
1273 loader
= PyObject_CallMethod(importer
,
1277 return NULL
; /* error */
1278 if (loader
!= Py_None
) {
1279 /* a loader was found */
1281 return &importhookdescr
;
1288 /* no hook was found, use builtin import */
1290 if (len
> 0 && buf
[len
-1] != SEP
1292 && buf
[len
-1] != ALTSEP
1296 strcpy(buf
+len
, name
);
1299 /* Check for package import (buf holds a directory name,
1300 and there's an __init__ module in that directory */
1302 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1303 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1304 case_ok(buf
, len
, namelen
, name
)) { /* case matches */
1305 if (find_init_module(buf
)) { /* and has __init__.py */
1310 char warnstr
[MAXPATHLEN
+80];
1311 sprintf(warnstr
, "Not importing directory "
1312 "'%.*s': missing __init__.py",
1314 if (PyErr_Warn(PyExc_ImportWarning
,
1322 /* XXX How are you going to test for directories? */
1325 case_ok(buf
, len
, namelen
, name
)) {
1326 if (find_init_module(buf
)) {
1331 char warnstr
[MAXPATHLEN
+80];
1332 sprintf(warnstr
, "Not importing directory "
1333 "'%.*s': missing __init__.py",
1335 if (PyErr_Warn(PyExc_ImportWarning
,
1343 #if defined(PYOS_OS2)
1344 /* take a snapshot of the module spec for restoration
1345 * after the 8 character DLL hackery
1347 saved_buf
= strdup(buf
);
1349 saved_namelen
= namelen
;
1350 #endif /* PYOS_OS2 */
1351 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1352 #if defined(PYOS_OS2)
1353 /* OS/2 limits DLLs to 8 character names (w/o
1355 * so if the name is longer than that and its a
1356 * dynamically loaded module we're going to try,
1357 * truncate the name before trying
1359 if (strlen(subname
) > 8) {
1360 /* is this an attempt to load a C extension? */
1361 const struct filedescr
*scan
;
1362 scan
= _PyImport_DynLoadFiletab
;
1363 while (scan
->suffix
!= NULL
) {
1364 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1369 if (scan
->suffix
!= NULL
) {
1370 /* yes, so truncate the name */
1372 len
-= strlen(subname
) - namelen
;
1376 #endif /* PYOS_OS2 */
1377 strcpy(buf
+len
, fdp
->suffix
);
1378 if (Py_VerboseFlag
> 1)
1379 PySys_WriteStderr("# trying %s\n", buf
);
1380 filemode
= fdp
->mode
;
1381 if (filemode
[0] == 'U')
1382 filemode
= "r" PY_STDIOTEXTMODE
;
1383 fp
= fopen(buf
, filemode
);
1385 if (case_ok(buf
, len
, namelen
, name
))
1387 else { /* continue search */
1392 #if defined(PYOS_OS2)
1393 /* restore the saved snapshot */
1394 strcpy(buf
, saved_buf
);
1396 namelen
= saved_namelen
;
1399 #if defined(PYOS_OS2)
1400 /* don't need/want the module name snapshot anymore */
1412 PyErr_Format(PyExc_ImportError
,
1413 "No module named %.200s", name
);
1420 /* Helpers for main.c
1421 * Find the source file corresponding to a named module
1424 _PyImport_FindModule(const char *name
, PyObject
*path
, char *buf
,
1425 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1427 return find_module((char *) name
, (char *) name
, path
,
1428 buf
, buflen
, p_fp
, p_loader
);
1431 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr
* fd
)
1433 return fd
->type
== PY_SOURCE
|| fd
->type
== PY_COMPILED
;
1436 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1437 * The arguments here are tricky, best shown by example:
1438 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1440 * |--------------------- buf ---------------------|
1441 * |------------------- len ------------------|
1442 * |------ name -------|
1443 * |----- namelen -----|
1444 * buf is the full path, but len only counts up to (& exclusive of) the
1445 * extension. name is the module name, also exclusive of extension.
1447 * We've already done a successful stat() or fopen() on buf, so know that
1448 * there's some match, possibly case-insensitive.
1450 * case_ok() is to return 1 if there's a case-sensitive match for
1451 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1454 * case_ok() is used to implement case-sensitive import semantics even
1455 * on platforms with case-insensitive filesystems. It's trivial to implement
1456 * for case-sensitive filesystems. It's pretty much a cross-platform
1457 * nightmare for systems with case-insensitive filesystems.
1460 /* First we may need a pile of platform-specific header files; the sequence
1461 * of #if's here should match the sequence in the body of case_ok().
1463 #if defined(MS_WINDOWS)
1464 #include <windows.h>
1466 #elif defined(DJGPP)
1469 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1470 #include <sys/types.h>
1473 #elif defined(PYOS_OS2)
1475 #define INCL_DOSERRORS
1476 #define INCL_NOPMAPI
1479 #elif defined(RISCOS)
1480 #include "oslib/osfscontrol.h"
1484 case_ok(char *buf
, Py_ssize_t len
, Py_ssize_t namelen
, char *name
)
1486 /* Pick a platform-specific implementation; the sequence of #if's here should
1487 * match the sequence just above.
1491 #if defined(MS_WINDOWS)
1492 WIN32_FIND_DATA data
;
1495 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1498 h
= FindFirstFile(buf
, &data
);
1499 if (h
== INVALID_HANDLE_VALUE
) {
1500 PyErr_Format(PyExc_NameError
,
1501 "Can't find file for module %.100s\n(filename %.300s)",
1506 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1509 #elif defined(DJGPP)
1513 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1516 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1518 PyErr_Format(PyExc_NameError
,
1519 "Can't find file for module %.100s\n(filename %.300s)",
1523 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1525 /* new-fangled macintosh (macosx) or Cygwin */
1526 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1529 char dirname
[MAXPATHLEN
+ 1];
1530 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1532 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1535 /* Copy the dir component into dirname; substitute "." if empty */
1541 assert(dirlen
<= MAXPATHLEN
);
1542 memcpy(dirname
, buf
, dirlen
);
1543 dirname
[dirlen
] = '\0';
1545 /* Open the directory and search the entries for an exact match. */
1546 dirp
= opendir(dirname
);
1548 char *nameWithExt
= buf
+ len
- namelen
;
1549 while ((dp
= readdir(dirp
)) != NULL
) {
1551 #ifdef _DIRENT_HAVE_D_NAMELEN
1556 if (thislen
>= namelen
&&
1557 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1558 (void)closedir(dirp
);
1559 return 1; /* Found */
1562 (void)closedir(dirp
);
1564 return 0 ; /* Not found */
1567 #elif defined(RISCOS)
1568 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1569 char buf2
[MAXPATHLEN
+2];
1570 char *nameWithExt
= buf
+len
-namelen
;
1574 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1578 append wildcard, otherwise case of filename wouldn't be touched */
1582 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1583 canonlen
= MAXPATHLEN
+1-canonlen
;
1584 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1586 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1587 return 1; /* match */
1592 #elif defined(PYOS_OS2)
1598 if (getenv("PYTHONCASEOK") != NULL
)
1601 rc
= DosFindFirst(buf
,
1603 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1604 &ffbuf
, sizeof(ffbuf
),
1609 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1611 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1620 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1622 find_init_module(char *buf
)
1624 const size_t save_len
= strlen(buf
);
1625 size_t i
= save_len
;
1626 char *pname
; /* pointer to start of __init__ */
1627 struct stat statbuf
;
1629 /* For calling case_ok(buf, len, namelen, name):
1630 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1632 * |--------------------- buf ---------------------|
1633 * |------------------- len ------------------|
1634 * |------ name -------|
1635 * |----- namelen -----|
1637 if (save_len
+ 13 >= MAXPATHLEN
)
1641 strcpy(pname
, "__init__.py");
1642 if (stat(buf
, &statbuf
) == 0) {
1644 save_len
+ 9, /* len("/__init__") */
1645 8, /* len("__init__") */
1647 buf
[save_len
] = '\0';
1652 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1653 if (stat(buf
, &statbuf
) == 0) {
1655 save_len
+ 9, /* len("/__init__") */
1656 8, /* len("__init__") */
1658 buf
[save_len
] = '\0';
1662 buf
[save_len
] = '\0';
1670 find_init_module(buf
)
1673 int save_len
= strlen(buf
);
1676 if (save_len
+ 13 >= MAXPATHLEN
)
1679 strcpy(buf
+i
, "__init__/py");
1681 buf
[save_len
] = '\0';
1685 if (Py_OptimizeFlag
)
1690 buf
[save_len
] = '\0';
1693 buf
[save_len
] = '\0';
1698 #endif /* HAVE_STAT */
1701 static int init_builtin(char *); /* Forward */
1703 /* Load an external module using the default search path and return
1704 its module object WITH INCREMENTED REFERENCE COUNT */
1707 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1713 /* First check that there's an open file (if we need one) */
1718 PyErr_Format(PyExc_ValueError
,
1719 "file object required for import (type code %d)",
1728 m
= load_source_module(name
, buf
, fp
);
1732 m
= load_compiled_module(name
, buf
, fp
);
1735 #ifdef HAVE_DYNAMIC_LOADING
1737 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1742 m
= load_package(name
, buf
);
1747 if (buf
!= NULL
&& buf
[0] != '\0')
1749 if (type
== C_BUILTIN
)
1750 err
= init_builtin(name
);
1752 err
= PyImport_ImportFrozenModule(name
);
1756 PyErr_Format(PyExc_ImportError
,
1757 "Purported %s module %.200s not found",
1759 "builtin" : "frozen",
1763 modules
= PyImport_GetModuleDict();
1764 m
= PyDict_GetItemString(modules
, name
);
1768 "%s module %.200s not properly initialized",
1770 "builtin" : "frozen",
1778 if (loader
== NULL
) {
1779 PyErr_SetString(PyExc_ImportError
,
1780 "import hook without loader");
1783 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1788 PyErr_Format(PyExc_ImportError
,
1789 "Don't know how to import %.200s (type code %d)",
1799 /* Initialize a built-in module.
1800 Return 1 for succes, 0 if the module is not found, and -1 with
1801 an exception set if the initialization failed. */
1804 init_builtin(char *name
)
1808 if (_PyImport_FindExtension(name
, name
) != NULL
)
1811 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1812 if (strcmp(name
, p
->name
) == 0) {
1813 if (p
->initfunc
== NULL
) {
1814 PyErr_Format(PyExc_ImportError
,
1815 "Cannot re-init internal module %.200s",
1820 PySys_WriteStderr("import %s # builtin\n", name
);
1822 if (PyErr_Occurred())
1824 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1833 /* Frozen modules */
1835 static struct _frozen
*
1836 find_frozen(char *name
)
1840 for (p
= PyImport_FrozenModules
; ; p
++) {
1841 if (p
->name
== NULL
)
1843 if (strcmp(p
->name
, name
) == 0)
1850 get_frozen_object(char *name
)
1852 struct _frozen
*p
= find_frozen(name
);
1856 PyErr_Format(PyExc_ImportError
,
1857 "No such frozen object named %.200s",
1861 if (p
->code
== NULL
) {
1862 PyErr_Format(PyExc_ImportError
,
1863 "Excluded frozen object named %.200s",
1870 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1873 /* Initialize a frozen module.
1874 Return 1 for succes, 0 if the module is not found, and -1 with
1875 an exception set if the initialization failed.
1876 This function is also used from frozenmain.c */
1879 PyImport_ImportFrozenModule(char *name
)
1881 struct _frozen
*p
= find_frozen(name
);
1889 if (p
->code
== NULL
) {
1890 PyErr_Format(PyExc_ImportError
,
1891 "Excluded frozen object named %.200s",
1896 ispackage
= (size
< 0);
1900 PySys_WriteStderr("import %s # frozen%s\n",
1901 name
, ispackage
? " package" : "");
1902 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1905 if (!PyCode_Check(co
)) {
1907 PyErr_Format(PyExc_TypeError
,
1908 "frozen object %.200s is not a code object",
1913 /* Set __path__ to the package name */
1916 m
= PyImport_AddModule(name
);
1919 d
= PyModule_GetDict(m
);
1920 s
= PyString_InternFromString(name
);
1923 err
= PyDict_SetItemString(d
, "__path__", s
);
1928 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1937 /* Import a module, either built-in, frozen, or external, and return
1938 its module object WITH INCREMENTED REFERENCE COUNT */
1941 PyImport_ImportModule(const char *name
)
1946 pname
= PyString_FromString(name
);
1949 result
= PyImport_Import(pname
);
1954 /* Forward declarations for helper routines */
1955 static PyObject
*get_parent(PyObject
*globals
, char *buf
,
1956 Py_ssize_t
*p_buflen
, int level
);
1957 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1958 char **p_name
, char *buf
, Py_ssize_t
*p_buflen
);
1959 static int mark_miss(char *name
);
1960 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1961 char *buf
, Py_ssize_t buflen
, int recursive
);
1962 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1964 /* The Magnum Opus of dotted-name import :-) */
1967 import_module_level(char *name
, PyObject
*globals
, PyObject
*locals
,
1968 PyObject
*fromlist
, int level
)
1970 char buf
[MAXPATHLEN
+1];
1971 Py_ssize_t buflen
= 0;
1972 PyObject
*parent
, *head
, *next
, *tail
;
1974 parent
= get_parent(globals
, buf
, &buflen
, level
);
1978 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1985 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1993 if (tail
== Py_None
) {
1994 /* If tail is Py_None, both get_parent and load_next found
1995 an empty module name: someone called __import__("") or
1996 doctored faulty bytecode */
1999 PyErr_SetString(PyExc_ValueError
,
2000 "Empty module name");
2004 if (fromlist
!= NULL
) {
2005 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
2009 if (fromlist
== NULL
) {
2015 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
2023 /* For DLL compatibility */
2024 #undef PyImport_ImportModuleEx
2026 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
2031 result
= import_module_level(name
, globals
, locals
, fromlist
, -1);
2032 if (unlock_import() < 0) {
2034 PyErr_SetString(PyExc_RuntimeError
,
2035 "not holding the import lock");
2040 #define PyImport_ImportModuleEx(n, g, l, f) \
2041 PyImport_ImportModuleLevel(n, g, l, f, -1);
2044 PyImport_ImportModuleLevel(char *name
, PyObject
*globals
, PyObject
*locals
,
2045 PyObject
*fromlist
, int level
)
2049 result
= import_module_level(name
, globals
, locals
, fromlist
, level
);
2050 if (unlock_import() < 0) {
2052 PyErr_SetString(PyExc_RuntimeError
,
2053 "not holding the import lock");
2059 /* Return the package that an import is being performed in. If globals comes
2060 from the module foo.bar.bat (not itself a package), this returns the
2061 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2062 the package's entry in sys.modules is returned, as a borrowed reference.
2064 The *name* of the returned package is returned in buf, with the length of
2065 the name in *p_buflen.
2067 If globals doesn't come from a package or a module in a package, or a
2068 corresponding entry is not found in sys.modules, Py_None is returned.
2071 get_parent(PyObject
*globals
, char *buf
, Py_ssize_t
*p_buflen
, int level
)
2073 static PyObject
*namestr
= NULL
;
2074 static PyObject
*pathstr
= NULL
;
2075 PyObject
*modname
, *modpath
, *modules
, *parent
;
2077 if (globals
== NULL
|| !PyDict_Check(globals
) || !level
)
2080 if (namestr
== NULL
) {
2081 namestr
= PyString_InternFromString("__name__");
2082 if (namestr
== NULL
)
2085 if (pathstr
== NULL
) {
2086 pathstr
= PyString_InternFromString("__path__");
2087 if (pathstr
== NULL
)
2093 modname
= PyDict_GetItem(globals
, namestr
);
2094 if (modname
== NULL
|| !PyString_Check(modname
))
2097 modpath
= PyDict_GetItem(globals
, pathstr
);
2098 if (modpath
!= NULL
) {
2099 Py_ssize_t len
= PyString_GET_SIZE(modname
);
2100 if (len
> MAXPATHLEN
) {
2101 PyErr_SetString(PyExc_ValueError
,
2102 "Module name too long");
2105 strcpy(buf
, PyString_AS_STRING(modname
));
2108 char *start
= PyString_AS_STRING(modname
);
2109 char *lastdot
= strrchr(start
, '.');
2111 if (lastdot
== NULL
&& level
> 0) {
2112 PyErr_SetString(PyExc_ValueError
,
2113 "Relative importpath too deep");
2116 if (lastdot
== NULL
)
2118 len
= lastdot
- start
;
2119 if (len
>= MAXPATHLEN
) {
2120 PyErr_SetString(PyExc_ValueError
,
2121 "Module name too long");
2124 strncpy(buf
, start
, len
);
2128 while (--level
> 0) {
2129 char *dot
= strrchr(buf
, '.');
2131 PyErr_SetString(PyExc_ValueError
,
2132 "Relative importpath too deep");
2137 *p_buflen
= strlen(buf
);
2139 modules
= PyImport_GetModuleDict();
2140 parent
= PyDict_GetItemString(modules
, buf
);
2142 PyErr_Format(PyExc_SystemError
,
2143 "Parent module '%.200s' not loaded", buf
);
2145 /* We expect, but can't guarantee, if parent != None, that:
2146 - parent.__name__ == buf
2147 - parent.__dict__ is globals
2148 If this is violated... Who cares? */
2151 /* altmod is either None or same as mod */
2153 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2154 Py_ssize_t
*p_buflen
)
2156 char *name
= *p_name
;
2157 char *dot
= strchr(name
, '.');
2162 if (strlen(name
) == 0) {
2163 /* completely empty module name should only happen in
2164 'from . import' (or '__import__("")')*/
2179 PyErr_SetString(PyExc_ValueError
,
2180 "Empty module name");
2184 p
= buf
+ *p_buflen
;
2187 if (p
+len
-buf
>= MAXPATHLEN
) {
2188 PyErr_SetString(PyExc_ValueError
,
2189 "Module name too long");
2192 strncpy(p
, name
, len
);
2194 *p_buflen
= p
+len
-buf
;
2196 result
= import_submodule(mod
, p
, buf
);
2197 if (result
== Py_None
&& altmod
!= mod
) {
2199 /* Here, altmod must be None and mod must not be None */
2200 result
= import_submodule(altmod
, p
, p
);
2201 if (result
!= NULL
&& result
!= Py_None
) {
2202 if (mark_miss(buf
) != 0) {
2206 strncpy(buf
, name
, len
);
2214 if (result
== Py_None
) {
2216 PyErr_Format(PyExc_ImportError
,
2217 "No module named %.200s", name
);
2225 mark_miss(char *name
)
2227 PyObject
*modules
= PyImport_GetModuleDict();
2228 return PyDict_SetItemString(modules
, name
, Py_None
);
2232 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, Py_ssize_t buflen
,
2237 if (!PyObject_HasAttrString(mod
, "__path__"))
2240 for (i
= 0; ; i
++) {
2241 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2244 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2250 if (!PyString_Check(item
)) {
2251 PyErr_SetString(PyExc_TypeError
,
2252 "Item in ``from list'' not a string");
2256 if (PyString_AS_STRING(item
)[0] == '*') {
2259 /* See if the package defines __all__ */
2261 continue; /* Avoid endless recursion */
2262 all
= PyObject_GetAttrString(mod
, "__all__");
2266 int ret
= ensure_fromlist(mod
, all
, buf
, buflen
, 1);
2273 hasit
= PyObject_HasAttr(mod
, item
);
2275 char *subname
= PyString_AS_STRING(item
);
2278 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2279 PyErr_SetString(PyExc_ValueError
,
2280 "Module name too long");
2287 submod
= import_submodule(mod
, subname
, buf
);
2289 if (submod
== NULL
) {
2301 add_submodule(PyObject
*mod
, PyObject
*submod
, char *fullname
, char *subname
,
2306 /* Irrespective of the success of this load, make a
2307 reference to it in the parent package module. A copy gets
2308 saved in the modules dictionary under the full name, so get a
2309 reference from there, if need be. (The exception is when the
2310 load failed with a SyntaxError -- then there's no trace in
2311 sys.modules. In that case, of course, do nothing extra.) */
2312 if (submod
== NULL
) {
2313 submod
= PyDict_GetItemString(modules
, fullname
);
2317 if (PyModule_Check(mod
)) {
2318 /* We can't use setattr here since it can give a
2319 * spurious warning if the submodule name shadows a
2321 PyObject
*dict
= PyModule_GetDict(mod
);
2324 if (PyDict_SetItemString(dict
, subname
, submod
) < 0)
2328 if (PyObject_SetAttrString(mod
, subname
, submod
) < 0)
2335 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2337 PyObject
*modules
= PyImport_GetModuleDict();
2341 if mod == None: subname == fullname
2342 else: mod.__name__ + "." + subname == fullname
2345 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2349 PyObject
*path
, *loader
= NULL
;
2350 char buf
[MAXPATHLEN
+1];
2351 struct filedescr
*fdp
;
2357 path
= PyObject_GetAttrString(mod
, "__path__");
2366 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2370 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2376 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2380 if (!add_submodule(mod
, m
, fullname
, subname
, modules
)) {
2390 /* Re-import a module of any kind and return its module object, WITH
2391 INCREMENTED REFERENCE COUNT */
2394 PyImport_ReloadModule(PyObject
*m
)
2396 PyObject
*modules
= PyImport_GetModuleDict();
2397 PyObject
*path
= NULL
, *loader
= NULL
;
2398 char *name
, *subname
;
2399 char buf
[MAXPATHLEN
+1];
2400 struct filedescr
*fdp
;
2404 if (m
== NULL
|| !PyModule_Check(m
)) {
2405 PyErr_SetString(PyExc_TypeError
,
2406 "reload() argument must be module");
2409 name
= PyModule_GetName(m
);
2412 if (m
!= PyDict_GetItemString(modules
, name
)) {
2413 PyErr_Format(PyExc_ImportError
,
2414 "reload(): module %.200s not in sys.modules",
2418 subname
= strrchr(name
, '.');
2419 if (subname
== NULL
)
2422 PyObject
*parentname
, *parent
;
2423 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2424 if (parentname
== NULL
)
2426 parent
= PyDict_GetItem(modules
, parentname
);
2427 if (parent
== NULL
) {
2428 PyErr_Format(PyExc_ImportError
,
2429 "reload(): parent %.200s not in sys.modules",
2430 PyString_AS_STRING(parentname
));
2431 Py_DECREF(parentname
);
2434 Py_DECREF(parentname
);
2436 path
= PyObject_GetAttrString(parent
, "__path__");
2441 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, &loader
);
2449 newm
= load_module(name
, fp
, buf
, fdp
->type
, loader
);
2455 /* load_module probably removed name from modules because of
2456 * the error. Put back the original module object. We're
2457 * going to return NULL in this case regardless of whether
2458 * replacing name succeeds, so the return value is ignored.
2460 PyDict_SetItemString(modules
, name
, m
);
2466 /* Higher-level import emulator which emulates the "import" statement
2467 more accurately -- it invokes the __import__() function from the
2468 builtins of the current globals. This means that the import is
2469 done using whatever import hooks are installed in the current
2470 environment, e.g. by "rexec".
2471 A dummy list ["__doc__"] is passed as the 4th argument so that
2472 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2473 will return <module "gencache"> instead of <module "win32com">. */
2476 PyImport_Import(PyObject
*module_name
)
2478 static PyObject
*silly_list
= NULL
;
2479 static PyObject
*builtins_str
= NULL
;
2480 static PyObject
*import_str
= NULL
;
2481 PyObject
*globals
= NULL
;
2482 PyObject
*import
= NULL
;
2483 PyObject
*builtins
= NULL
;
2486 /* Initialize constant string objects */
2487 if (silly_list
== NULL
) {
2488 import_str
= PyString_InternFromString("__import__");
2489 if (import_str
== NULL
)
2491 builtins_str
= PyString_InternFromString("__builtins__");
2492 if (builtins_str
== NULL
)
2494 silly_list
= Py_BuildValue("[s]", "__doc__");
2495 if (silly_list
== NULL
)
2499 /* Get the builtins from current globals */
2500 globals
= PyEval_GetGlobals();
2501 if (globals
!= NULL
) {
2503 builtins
= PyObject_GetItem(globals
, builtins_str
);
2504 if (builtins
== NULL
)
2508 /* No globals -- use standard builtins, and fake globals */
2511 builtins
= PyImport_ImportModuleLevel("__builtin__",
2512 NULL
, NULL
, NULL
, 0);
2513 if (builtins
== NULL
)
2515 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2516 if (globals
== NULL
)
2520 /* Get the __import__ function from the builtins */
2521 if (PyDict_Check(builtins
)) {
2522 import
= PyObject_GetItem(builtins
, import_str
);
2524 PyErr_SetObject(PyExc_KeyError
, import_str
);
2527 import
= PyObject_GetAttr(builtins
, import_str
);
2531 /* Call the _import__ function with the proper argument list */
2532 r
= PyObject_CallFunctionObjArgs(import
, module_name
, globals
,
2533 globals
, silly_list
, NULL
);
2536 Py_XDECREF(globals
);
2537 Py_XDECREF(builtins
);
2544 /* Module 'imp' provides Python access to the primitives used for
2549 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2553 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2554 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2555 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2556 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2558 return PyString_FromStringAndSize(buf
, 4);
2562 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2565 struct filedescr
*fdp
;
2567 list
= PyList_New(0);
2570 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2571 PyObject
*item
= Py_BuildValue("ssi",
2572 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2577 if (PyList_Append(list
, item
) < 0) {
2588 call_find_module(char *name
, PyObject
*path
)
2590 extern int fclose(FILE *);
2591 PyObject
*fob
, *ret
;
2592 struct filedescr
*fdp
;
2593 char pathname
[MAXPATHLEN
+1];
2597 if (path
== Py_None
)
2599 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2603 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2613 ret
= Py_BuildValue("Os(ssi)",
2614 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2620 imp_find_module(PyObject
*self
, PyObject
*args
)
2623 PyObject
*path
= NULL
;
2624 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2626 return call_find_module(name
, path
);
2630 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2635 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2637 ret
= init_builtin(name
);
2644 m
= PyImport_AddModule(name
);
2650 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2655 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2657 ret
= PyImport_ImportFrozenModule(name
);
2664 m
= PyImport_AddModule(name
);
2670 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2674 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2676 return get_frozen_object(name
);
2680 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2683 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2685 return PyInt_FromLong(is_builtin(name
));
2689 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2693 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2695 p
= find_frozen(name
);
2696 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2700 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2705 mode
= "r" PY_STDIOTEXTMODE
;
2706 fp
= fopen(pathname
, mode
);
2708 PyErr_SetFromErrno(PyExc_IOError
);
2711 fp
= PyFile_AsFile(fob
);
2713 PyErr_SetString(PyExc_ValueError
,
2714 "bad/closed file object");
2720 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2724 PyObject
*fob
= NULL
;
2727 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2728 &PyFile_Type
, &fob
))
2730 fp
= get_file(pathname
, fob
, "rb");
2733 m
= load_compiled_module(name
, pathname
, fp
);
2739 #ifdef HAVE_DYNAMIC_LOADING
2742 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2746 PyObject
*fob
= NULL
;
2749 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2750 &PyFile_Type
, &fob
))
2753 fp
= get_file(pathname
, fob
, "r");
2757 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2761 #endif /* HAVE_DYNAMIC_LOADING */
2764 imp_load_source(PyObject
*self
, PyObject
*args
)
2768 PyObject
*fob
= NULL
;
2771 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2772 &PyFile_Type
, &fob
))
2774 fp
= get_file(pathname
, fob
, "r");
2777 m
= load_source_module(name
, pathname
, fp
);
2784 imp_load_module(PyObject
*self
, PyObject
*args
)
2789 char *suffix
; /* Unused */
2794 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2795 &name
, &fob
, &pathname
,
2796 &suffix
, &mode
, &type
))
2799 /* Mode must start with 'r' or 'U' and must not contain '+'.
2800 Implicit in this test is the assumption that the mode
2801 may contain other modifiers like 'b' or 't'. */
2803 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2804 PyErr_Format(PyExc_ValueError
,
2805 "invalid file open mode %.200s", mode
);
2812 if (!PyFile_Check(fob
)) {
2813 PyErr_SetString(PyExc_ValueError
,
2814 "load_module arg#2 should be a file or None");
2817 fp
= get_file(pathname
, fob
, mode
);
2821 return load_module(name
, fp
, pathname
, type
, NULL
);
2825 imp_load_package(PyObject
*self
, PyObject
*args
)
2829 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2831 return load_package(name
, pathname
);
2835 imp_new_module(PyObject
*self
, PyObject
*args
)
2838 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2840 return PyModule_New(name
);
2845 PyDoc_STRVAR(doc_imp
,
2846 "This module provides the components needed to build your own\n\
2847 __import__ function. Undocumented functions are obsolete.");
2849 PyDoc_STRVAR(doc_find_module
,
2850 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2851 Search for a module. If path is omitted or None, search for a\n\
2852 built-in, frozen or special module and continue search in sys.path.\n\
2853 The module name cannot contain '.'; to search for a submodule of a\n\
2854 package, pass the submodule name and the package's __path__.");
2856 PyDoc_STRVAR(doc_load_module
,
2857 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2858 Load a module, given information returned by find_module().\n\
2859 The module name must include the full package name, if any.");
2861 PyDoc_STRVAR(doc_get_magic
,
2862 "get_magic() -> string\n\
2863 Return the magic number for .pyc or .pyo files.");
2865 PyDoc_STRVAR(doc_get_suffixes
,
2866 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2867 Return a list of (suffix, mode, type) tuples describing the files\n\
2868 that find_module() looks for.");
2870 PyDoc_STRVAR(doc_new_module
,
2871 "new_module(name) -> module\n\
2872 Create a new module. Do not enter it in sys.modules.\n\
2873 The module name must include the full package name, if any.");
2875 PyDoc_STRVAR(doc_lock_held
,
2876 "lock_held() -> boolean\n\
2877 Return True if the import lock is currently held, else False.\n\
2878 On platforms without threads, return False.");
2880 PyDoc_STRVAR(doc_acquire_lock
,
2881 "acquire_lock() -> None\n\
2882 Acquires the interpreter's import lock for the current thread.\n\
2883 This lock should be used by import hooks to ensure thread-safety\n\
2884 when importing modules.\n\
2885 On platforms without threads, this function does nothing.");
2887 PyDoc_STRVAR(doc_release_lock
,
2888 "release_lock() -> None\n\
2889 Release the interpreter's import lock.\n\
2890 On platforms without threads, this function does nothing.");
2892 static PyMethodDef imp_methods
[] = {
2893 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2894 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
2895 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
2896 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2897 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2898 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
2899 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
2900 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
2901 /* The rest are obsolete */
2902 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2903 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2904 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2905 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2906 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2907 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2908 #ifdef HAVE_DYNAMIC_LOADING
2909 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2911 {"load_package", imp_load_package
, METH_VARARGS
},
2912 {"load_source", imp_load_source
, METH_VARARGS
},
2913 {NULL
, NULL
} /* sentinel */
2917 setint(PyObject
*d
, char *name
, int value
)
2922 v
= PyInt_FromLong((long)value
);
2923 err
= PyDict_SetItemString(d
, name
, v
);
2933 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2934 NULL
, PYTHON_API_VERSION
);
2937 d
= PyModule_GetDict(m
);
2939 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2940 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2941 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2942 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2943 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2944 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2945 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2946 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2947 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2948 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
2955 /* API for embedding applications that want to add their own entries
2956 to the table of built-in modules. This should normally be called
2957 *before* Py_Initialize(). When the table resize fails, -1 is
2958 returned and the existing table is unchanged.
2960 After a similar function by Just van Rossum. */
2963 PyImport_ExtendInittab(struct _inittab
*newtab
)
2965 static struct _inittab
*our_copy
= NULL
;
2969 /* Count the number of entries in both tables */
2970 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2973 return 0; /* Nothing to do */
2974 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2977 /* Allocate new memory for the combined table */
2979 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2983 /* Copy the tables into the new memory */
2984 if (our_copy
!= PyImport_Inittab
)
2985 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2986 PyImport_Inittab
= our_copy
= p
;
2987 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2992 /* Shorthand to add a single entry given a name and a function */
2995 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2997 struct _inittab newtab
[2];
2999 memset(newtab
, '\0', sizeof newtab
);
3001 newtab
[0].name
= name
;
3002 newtab
[0].initfunc
= initfunc
;
3004 return PyImport_ExtendInittab(newtab
);