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)
63 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
64 Python 2.5b3: 62111 (fix wrong code: x += yield)
65 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
66 storing constants that should have been removed)
67 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
68 Python 2.6a0: 62141 (peephole optimizations)
71 #define MAGIC (62141 | ((long)'\r'<<16) | ((long)'\n'<<24))
73 /* Magic word as global; note that _PyImport_Init() can change the
74 value of this global to accommodate for alterations of how the
75 compiler works which are enabled by command line switches. */
76 static long pyc_magic
= MAGIC
;
78 /* See _PyImport_FixupExtension() below */
79 static PyObject
*extensions
= NULL
;
81 /* This table is defined in config.c: */
82 extern struct _inittab _PyImport_Inittab
[];
84 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
86 /* these tables define the module suffixes that Python recognizes */
87 struct filedescr
* _PyImport_Filetab
= NULL
;
90 static const struct filedescr _PyImport_StandardFiletab
[] = {
91 {"/py", "U", PY_SOURCE
},
92 {"/pyc", "rb", PY_COMPILED
},
96 static const struct filedescr _PyImport_StandardFiletab
[] = {
97 {".py", "U", PY_SOURCE
},
99 {".pyw", "U", PY_SOURCE
},
101 {".pyc", "rb", PY_COMPILED
},
106 static PyTypeObject NullImporterType
; /* Forward reference */
108 /* Initialize things */
113 const struct filedescr
*scan
;
114 struct filedescr
*filetab
;
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
121 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
123 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
125 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
127 Py_FatalError("Can't initialize import file table.");
128 memcpy(filetab
, _PyImport_DynLoadFiletab
,
129 countD
* sizeof(struct filedescr
));
130 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
131 countS
* sizeof(struct filedescr
));
132 filetab
[countD
+ countS
].suffix
= NULL
;
134 _PyImport_Filetab
= filetab
;
136 if (Py_OptimizeFlag
) {
137 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
138 for (; filetab
->suffix
!= NULL
; filetab
++) {
140 if (strcmp(filetab
->suffix
, ".pyc") == 0)
141 filetab
->suffix
= ".pyo";
143 if (strcmp(filetab
->suffix
, "/pyc") == 0)
144 filetab
->suffix
= "/pyo";
149 if (Py_UnicodeFlag
) {
150 /* Fix the pyc_magic so that byte compiled code created
151 using the all-Unicode method doesn't interfere with
152 code created in normal operation mode. */
153 pyc_magic
= MAGIC
+ 1;
158 _PyImportHooks_Init(void)
160 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
163 /* adding sys.path_hooks and sys.path_importer_cache, setting up
165 if (PyType_Ready(&NullImporterType
) < 0)
169 PySys_WriteStderr("# installing zipimport hook\n");
174 err
= PySys_SetObject("meta_path", v
);
181 err
= PySys_SetObject("path_importer_cache", v
);
185 path_hooks
= PyList_New(0);
186 if (path_hooks
== NULL
)
188 err
= PySys_SetObject("path_hooks", path_hooks
);
192 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
193 "path_importer_cache, or NullImporter failed"
197 zimpimport
= PyImport_ImportModule("zipimport");
198 if (zimpimport
== NULL
) {
199 PyErr_Clear(); /* No zip import module -- okay */
201 PySys_WriteStderr("# can't import zipimport\n");
204 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
206 Py_DECREF(zimpimport
);
207 if (zipimporter
== NULL
) {
208 PyErr_Clear(); /* No zipimporter object -- okay */
211 "# can't import zipimport.zipimporter\n");
214 /* sys.path_hooks.append(zipimporter) */
215 err
= PyList_Append(path_hooks
, zipimporter
);
216 Py_DECREF(zipimporter
);
221 "# installed zipimport hook\n");
224 Py_DECREF(path_hooks
);
230 Py_XDECREF(extensions
);
232 PyMem_DEL(_PyImport_Filetab
);
233 _PyImport_Filetab
= NULL
;
237 /* Locking primitives to prevent parallel imports of the same module
238 in different threads to return with a partially loaded module.
239 These calls are serialized by the global interpreter lock. */
243 #include "pythread.h"
245 static PyThread_type_lock import_lock
= 0;
246 static long import_lock_thread
= -1;
247 static int import_lock_level
= 0;
252 long me
= PyThread_get_thread_ident();
254 return; /* Too bad */
255 if (import_lock
== NULL
) {
256 import_lock
= PyThread_allocate_lock();
257 if (import_lock
== NULL
)
258 return; /* Nothing much we can do. */
260 if (import_lock_thread
== me
) {
264 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
266 PyThreadState
*tstate
= PyEval_SaveThread();
267 PyThread_acquire_lock(import_lock
, 1);
268 PyEval_RestoreThread(tstate
);
270 import_lock_thread
= me
;
271 import_lock_level
= 1;
277 long me
= PyThread_get_thread_ident();
278 if (me
== -1 || import_lock
== NULL
)
279 return 0; /* Too bad */
280 if (import_lock_thread
!= me
)
283 if (import_lock_level
== 0) {
284 import_lock_thread
= -1;
285 PyThread_release_lock(import_lock
);
290 /* This function is called from PyOS_AfterFork to ensure that newly
291 created child processes do not share locks with the parent. */
294 _PyImport_ReInitLock(void)
297 if (import_lock
!= NULL
)
298 import_lock
= PyThread_allocate_lock();
304 #define lock_import()
305 #define unlock_import() 0
310 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
313 return PyBool_FromLong(import_lock_thread
!= -1);
315 return PyBool_FromLong(0);
320 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
330 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
333 if (unlock_import() < 0) {
334 PyErr_SetString(PyExc_RuntimeError
,
335 "not holding the import lock");
346 PyImport_GetModuleDict(void)
348 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
349 if (interp
->modules
== NULL
)
350 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
351 return interp
->modules
;
355 /* List of names to clear in sys */
356 static char* sys_deletes
[] = {
357 "path", "argv", "ps1", "ps2", "exitfunc",
358 "exc_type", "exc_value", "exc_traceback",
359 "last_type", "last_value", "last_traceback",
360 "path_hooks", "path_importer_cache", "meta_path",
364 static char* sys_files
[] = {
365 "stdin", "__stdin__",
366 "stdout", "__stdout__",
367 "stderr", "__stderr__",
372 /* Un-initialize things, as good as we can */
375 PyImport_Cleanup(void)
377 Py_ssize_t pos
, ndone
;
379 PyObject
*key
, *value
, *dict
;
380 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
381 PyObject
*modules
= interp
->modules
;
384 return; /* Already done */
386 /* Delete some special variables first. These are common
387 places where user values hide and people complain when their
388 destructors fail. Since the modules containing them are
389 deleted *last* of all, they would come too late in the normal
390 destruction order. Sigh. */
392 value
= PyDict_GetItemString(modules
, "__builtin__");
393 if (value
!= NULL
&& PyModule_Check(value
)) {
394 dict
= PyModule_GetDict(value
);
396 PySys_WriteStderr("# clear __builtin__._\n");
397 PyDict_SetItemString(dict
, "_", Py_None
);
399 value
= PyDict_GetItemString(modules
, "sys");
400 if (value
!= NULL
&& PyModule_Check(value
)) {
403 dict
= PyModule_GetDict(value
);
404 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
406 PySys_WriteStderr("# clear sys.%s\n", *p
);
407 PyDict_SetItemString(dict
, *p
, Py_None
);
409 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
411 PySys_WriteStderr("# restore sys.%s\n", *p
);
412 v
= PyDict_GetItemString(dict
, *(p
+1));
415 PyDict_SetItemString(dict
, *p
, v
);
419 /* First, delete __main__ */
420 value
= PyDict_GetItemString(modules
, "__main__");
421 if (value
!= NULL
&& PyModule_Check(value
)) {
423 PySys_WriteStderr("# cleanup __main__\n");
424 _PyModule_Clear(value
);
425 PyDict_SetItemString(modules
, "__main__", Py_None
);
428 /* The special treatment of __builtin__ here is because even
429 when it's not referenced as a module, its dictionary is
430 referenced by almost every module's __builtins__. Since
431 deleting a module clears its dictionary (even if there are
432 references left to it), we need to delete the __builtin__
433 module last. Likewise, we don't delete sys until the very
434 end because it is implicitly referenced (e.g. by print).
436 Also note that we 'delete' modules by replacing their entry
437 in the modules dict with None, rather than really deleting
438 them; this avoids a rehash of the modules dictionary and
439 also marks them as "non existent" so they won't be
442 /* Next, repeatedly delete modules with a reference count of
443 one (skipping __builtin__ and sys) and delete them */
447 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
448 if (value
->ob_refcnt
!= 1)
450 if (PyString_Check(key
) && PyModule_Check(value
)) {
451 name
= PyString_AS_STRING(key
);
452 if (strcmp(name
, "__builtin__") == 0)
454 if (strcmp(name
, "sys") == 0)
458 "# cleanup[1] %s\n", name
);
459 _PyModule_Clear(value
);
460 PyDict_SetItem(modules
, key
, Py_None
);
466 /* Next, delete all modules (still skipping __builtin__ and sys) */
468 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
469 if (PyString_Check(key
) && PyModule_Check(value
)) {
470 name
= PyString_AS_STRING(key
);
471 if (strcmp(name
, "__builtin__") == 0)
473 if (strcmp(name
, "sys") == 0)
476 PySys_WriteStderr("# cleanup[2] %s\n", name
);
477 _PyModule_Clear(value
);
478 PyDict_SetItem(modules
, key
, Py_None
);
482 /* Next, delete sys and __builtin__ (in that order) */
483 value
= PyDict_GetItemString(modules
, "sys");
484 if (value
!= NULL
&& PyModule_Check(value
)) {
486 PySys_WriteStderr("# cleanup sys\n");
487 _PyModule_Clear(value
);
488 PyDict_SetItemString(modules
, "sys", Py_None
);
490 value
= PyDict_GetItemString(modules
, "__builtin__");
491 if (value
!= NULL
&& PyModule_Check(value
)) {
493 PySys_WriteStderr("# cleanup __builtin__\n");
494 _PyModule_Clear(value
);
495 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
498 /* Finally, clear and delete the modules directory */
499 PyDict_Clear(modules
);
500 interp
->modules
= NULL
;
505 /* Helper for pythonrun.c -- return magic number */
508 PyImport_GetMagicNumber(void)
514 /* Magic for extension modules (built-in as well as dynamically
515 loaded). To prevent initializing an extension module more than
516 once, we keep a static dictionary 'extensions' keyed by module name
517 (for built-in modules) or by filename (for dynamically loaded
518 modules), containing these modules. A copy of the module's
519 dictionary is stored by calling _PyImport_FixupExtension()
520 immediately after the module initialization function succeeds. A
521 copy can be retrieved from there by calling
522 _PyImport_FindExtension(). */
525 _PyImport_FixupExtension(char *name
, char *filename
)
527 PyObject
*modules
, *mod
, *dict
, *copy
;
528 if (extensions
== NULL
) {
529 extensions
= PyDict_New();
530 if (extensions
== NULL
)
533 modules
= PyImport_GetModuleDict();
534 mod
= PyDict_GetItemString(modules
, name
);
535 if (mod
== NULL
|| !PyModule_Check(mod
)) {
536 PyErr_Format(PyExc_SystemError
,
537 "_PyImport_FixupExtension: module %.200s not loaded", name
);
540 dict
= PyModule_GetDict(mod
);
543 copy
= PyDict_Copy(dict
);
546 PyDict_SetItemString(extensions
, filename
, copy
);
552 _PyImport_FindExtension(char *name
, char *filename
)
554 PyObject
*dict
, *mod
, *mdict
;
555 if (extensions
== NULL
)
557 dict
= PyDict_GetItemString(extensions
, filename
);
560 mod
= PyImport_AddModule(name
);
563 mdict
= PyModule_GetDict(mod
);
566 if (PyDict_Update(mdict
, dict
))
569 PySys_WriteStderr("import %s # previously loaded (%s)\n",
575 /* Get the module object corresponding to a module name.
576 First check the modules dictionary if there's one there,
577 if not, create a new one and insert it in the modules dictionary.
578 Because the former action is most common, THIS DOES NOT RETURN A
582 PyImport_AddModule(const char *name
)
584 PyObject
*modules
= PyImport_GetModuleDict();
587 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
590 m
= PyModule_New(name
);
593 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
597 Py_DECREF(m
); /* Yes, it still exists, in modules! */
602 /* Remove name from sys.modules, if it's there. */
604 _RemoveModule(const char *name
)
606 PyObject
*modules
= PyImport_GetModuleDict();
607 if (PyDict_GetItemString(modules
, name
) == NULL
)
609 if (PyDict_DelItemString(modules
, name
) < 0)
610 Py_FatalError("import: deleting existing key in"
611 "sys.modules failed");
614 /* Execute a code object in a module and return the module object
615 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
616 * removed from sys.modules, to avoid leaving damaged module objects
617 * in sys.modules. The caller may wish to restore the original
618 * module object (if any) in this case; PyImport_ReloadModule is an
622 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
624 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
628 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
630 PyObject
*modules
= PyImport_GetModuleDict();
633 m
= PyImport_AddModule(name
);
636 /* If the module is being reloaded, we get the old module back
637 and re-use its dict to exec the new code. */
638 d
= PyModule_GetDict(m
);
639 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
640 if (PyDict_SetItemString(d
, "__builtins__",
641 PyEval_GetBuiltins()) != 0)
644 /* Remember the filename as the __file__ attribute */
646 if (pathname
!= NULL
) {
647 v
= PyString_FromString(pathname
);
652 v
= ((PyCodeObject
*)co
)->co_filename
;
655 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
656 PyErr_Clear(); /* Not important enough to report */
659 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
664 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
665 PyErr_Format(PyExc_ImportError
,
666 "Loaded module %.200s not found in sys.modules",
681 /* Given a pathname for a Python source file, fill a buffer with the
682 pathname for the corresponding compiled file. Return the pathname
683 for the compiled file, or NULL if there's no space in the buffer.
684 Doesn't set an exception. */
687 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
689 size_t len
= strlen(pathname
);
694 /* Treat .pyw as if it were .py. The case of ".pyw" must match
695 that used in _PyImport_StandardFiletab. */
696 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
697 --len
; /* pretend 'w' isn't there */
699 memcpy(buf
, pathname
, len
);
700 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
707 /* Given a pathname for a Python source file, its time of last
708 modification, and a pathname for a compiled file, check whether the
709 compiled file represents the same version of the source. If so,
710 return a FILE pointer for the compiled file, positioned just after
711 the header; if not, return NULL.
712 Doesn't set an exception. */
715 check_compiled_module(char *pathname
, time_t mtime
, char *cpathname
)
721 fp
= fopen(cpathname
, "rb");
724 magic
= PyMarshal_ReadLongFromFile(fp
);
725 if (magic
!= pyc_magic
) {
727 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
731 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
732 if (pyc_mtime
!= mtime
) {
734 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
739 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
744 /* Read a code object from a file and check it for validity */
746 static PyCodeObject
*
747 read_compiled_module(char *cpathname
, FILE *fp
)
751 co
= PyMarshal_ReadLastObjectFromFile(fp
);
754 if (!PyCode_Check(co
)) {
755 PyErr_Format(PyExc_ImportError
,
756 "Non-code object in %.200s", cpathname
);
760 return (PyCodeObject
*)co
;
764 /* Load a module from a compiled file, execute it, and return its
765 module object WITH INCREMENTED REFERENCE COUNT */
768 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
774 magic
= PyMarshal_ReadLongFromFile(fp
);
775 if (magic
!= pyc_magic
) {
776 PyErr_Format(PyExc_ImportError
,
777 "Bad magic number in %.200s", cpathname
);
780 (void) PyMarshal_ReadLongFromFile(fp
);
781 co
= read_compiled_module(cpathname
, fp
);
785 PySys_WriteStderr("import %s # precompiled from %s\n",
787 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
793 /* Parse a source file and return the corresponding code object */
795 static PyCodeObject
*
796 parse_source_module(const char *pathname
, FILE *fp
)
798 PyCodeObject
*co
= NULL
;
800 PyArena
*arena
= PyArena_New();
804 mod
= PyParser_ASTFromFile(fp
, pathname
, Py_file_input
, 0, 0, 0,
807 co
= PyAST_Compile(mod
, pathname
, NULL
, arena
);
814 /* Helper to open a bytecode file for writing in exclusive mode */
817 open_exclusive(char *filename
)
819 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
820 /* Use O_EXCL to avoid a race condition when another process tries to
821 write the same file. When that happens, our open() call fails,
822 which is just fine (since it's only a cache).
823 XXX If the file exists and is writable but the directory is not
824 writable, the file will never be written. Oh well.
827 (void) unlink(filename
);
828 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
830 |O_BINARY
/* necessary for Windows */
833 , 0666, "ctxt=bin", "shr=nil"
840 return fdopen(fd
, "wb");
842 /* Best we can do -- on Windows this can't happen anyway */
843 return fopen(filename
, "wb");
848 /* Write a compiled module to a file, placing the time of last
849 modification of its source into the header.
850 Errors are ignored, if a write error occurs an attempt is made to
854 write_compiled_module(PyCodeObject
*co
, char *cpathname
, time_t mtime
)
858 fp
= open_exclusive(cpathname
);
862 "# can't create %s\n", cpathname
);
865 PyMarshal_WriteLongToFile(pyc_magic
, fp
, Py_MARSHAL_VERSION
);
866 /* First write a 0 for mtime */
867 PyMarshal_WriteLongToFile(0L, fp
, Py_MARSHAL_VERSION
);
868 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
, Py_MARSHAL_VERSION
);
869 if (fflush(fp
) != 0 || ferror(fp
)) {
871 PySys_WriteStderr("# can't write %s\n", cpathname
);
872 /* Don't keep partial file */
874 (void) unlink(cpathname
);
877 /* Now write the true mtime */
879 assert(mtime
< LONG_MAX
);
880 PyMarshal_WriteLongToFile((long)mtime
, fp
, Py_MARSHAL_VERSION
);
884 PySys_WriteStderr("# wrote %s\n", cpathname
);
888 /* Load a source module from a given file and return its module
889 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
890 byte-compiled file, use that instead. */
893 load_source_module(char *name
, char *pathname
, FILE *fp
)
897 char buf
[MAXPATHLEN
+1];
902 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
903 if (mtime
== (time_t)(-1)) {
904 PyErr_Format(PyExc_RuntimeError
,
905 "unable to get modification time from '%s'",
909 #if SIZEOF_TIME_T > 4
910 /* Python's .pyc timestamp handling presumes that the timestamp fits
911 in 4 bytes. This will be fine until sometime in the year 2038,
912 when a 4-byte signed time_t will overflow.
915 PyErr_SetString(PyExc_OverflowError
,
916 "modification time overflows a 4 byte field");
920 cpathname
= make_compiled_pathname(pathname
, buf
,
921 (size_t)MAXPATHLEN
+ 1);
922 if (cpathname
!= NULL
&&
923 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
924 co
= read_compiled_module(cpathname
, fpc
);
929 PySys_WriteStderr("import %s # precompiled from %s\n",
931 pathname
= cpathname
;
934 co
= parse_source_module(pathname
, fp
);
938 PySys_WriteStderr("import %s # from %s\n",
941 write_compiled_module(co
, cpathname
, mtime
);
943 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
951 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
952 static struct filedescr
*find_module(char *, char *, PyObject
*,
953 char *, size_t, FILE **, PyObject
**);
954 static struct _frozen
*find_frozen(char *name
);
956 /* Load a package and return its module object WITH INCREMENTED
960 load_package(char *name
, char *pathname
)
963 PyObject
*file
= NULL
;
964 PyObject
*path
= NULL
;
966 char buf
[MAXPATHLEN
+1];
968 struct filedescr
*fdp
;
970 m
= PyImport_AddModule(name
);
974 PySys_WriteStderr("import %s # directory %s\n",
976 d
= PyModule_GetDict(m
);
977 file
= PyString_FromString(pathname
);
980 path
= Py_BuildValue("[O]", file
);
983 err
= PyDict_SetItemString(d
, "__file__", file
);
985 err
= PyDict_SetItemString(d
, "__path__", path
);
989 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
991 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
999 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
1013 /* Helper to test for built-in module */
1016 is_builtin(char *name
)
1019 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
1020 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
1021 if (PyImport_Inittab
[i
].initfunc
== NULL
)
1031 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1032 possibly by fetching it from the path_importer_cache dict. If it
1033 wasn't yet cached, traverse path_hooks until a hook is found
1034 that can handle the path item. Return None if no hook could;
1035 this tells our caller it should fall back to the builtin
1036 import mechanism. Cache the result in path_importer_cache.
1037 Returns a borrowed reference. */
1040 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
1044 Py_ssize_t j
, nhooks
;
1046 /* These conditions are the caller's responsibility: */
1047 assert(PyList_Check(path_hooks
));
1048 assert(PyDict_Check(path_importer_cache
));
1050 nhooks
= PyList_Size(path_hooks
);
1052 return NULL
; /* Shouldn't happen */
1054 importer
= PyDict_GetItem(path_importer_cache
, p
);
1055 if (importer
!= NULL
)
1058 /* set path_importer_cache[p] to None to avoid recursion */
1059 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1062 for (j
= 0; j
< nhooks
; j
++) {
1063 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1066 importer
= PyObject_CallFunctionObjArgs(hook
, p
, NULL
);
1067 if (importer
!= NULL
)
1070 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1075 if (importer
== NULL
) {
1076 importer
= PyObject_CallFunctionObjArgs(
1077 (PyObject
*)&NullImporterType
, p
, NULL
1079 if (importer
== NULL
) {
1080 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1086 if (importer
!= NULL
) {
1087 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1088 Py_DECREF(importer
);
1095 /* Search the path (default sys.path) for a module. Return the
1096 corresponding filedescr struct, and (via return arguments) the
1097 pathname and an open file. Return NULL if the module is not found. */
1100 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1101 char *, Py_ssize_t
);
1104 static int case_ok(char *, Py_ssize_t
, Py_ssize_t
, char *);
1105 static int find_init_module(char *); /* Forward */
1106 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1108 static struct filedescr
*
1109 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1110 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1112 Py_ssize_t i
, npath
;
1113 size_t len
, namelen
;
1114 struct filedescr
*fdp
= NULL
;
1117 PyObject
*path_hooks
, *path_importer_cache
;
1119 struct stat statbuf
;
1121 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1122 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1123 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1124 char name
[MAXPATHLEN
+1];
1125 #if defined(PYOS_OS2)
1127 size_t saved_namelen
;
1128 char *saved_buf
= NULL
;
1130 if (p_loader
!= NULL
)
1133 if (strlen(subname
) > MAXPATHLEN
) {
1134 PyErr_SetString(PyExc_OverflowError
,
1135 "module name is too long");
1138 strcpy(name
, subname
);
1140 /* sys.meta_path import hook */
1141 if (p_loader
!= NULL
) {
1142 PyObject
*meta_path
;
1144 meta_path
= PySys_GetObject("meta_path");
1145 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1146 PyErr_SetString(PyExc_ImportError
,
1147 "sys.meta_path must be a list of "
1151 Py_INCREF(meta_path
); /* zap guard */
1152 npath
= PyList_Size(meta_path
);
1153 for (i
= 0; i
< npath
; i
++) {
1155 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1156 loader
= PyObject_CallMethod(hook
, "find_module",
1160 if (loader
== NULL
) {
1161 Py_DECREF(meta_path
);
1162 return NULL
; /* true error */
1164 if (loader
!= Py_None
) {
1165 /* a loader was found */
1167 Py_DECREF(meta_path
);
1168 return &importhookdescr
;
1172 Py_DECREF(meta_path
);
1175 if (path
!= NULL
&& PyString_Check(path
)) {
1176 /* The only type of submodule allowed inside a "frozen"
1177 package are other frozen modules or packages. */
1178 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1179 PyErr_SetString(PyExc_ImportError
,
1180 "full frozen module name too long");
1183 strcpy(buf
, PyString_AsString(path
));
1187 if (find_frozen(name
) != NULL
) {
1191 PyErr_Format(PyExc_ImportError
,
1192 "No frozen submodule named %.200s", name
);
1196 if (is_builtin(name
)) {
1200 if ((find_frozen(name
)) != NULL
) {
1206 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1212 path
= PySys_GetObject("path");
1214 if (path
== NULL
|| !PyList_Check(path
)) {
1215 PyErr_SetString(PyExc_ImportError
,
1216 "sys.path must be a list of directory names");
1220 path_hooks
= PySys_GetObject("path_hooks");
1221 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1222 PyErr_SetString(PyExc_ImportError
,
1223 "sys.path_hooks must be a list of "
1227 path_importer_cache
= PySys_GetObject("path_importer_cache");
1228 if (path_importer_cache
== NULL
||
1229 !PyDict_Check(path_importer_cache
)) {
1230 PyErr_SetString(PyExc_ImportError
,
1231 "sys.path_importer_cache must be a dict");
1235 npath
= PyList_Size(path
);
1236 namelen
= strlen(name
);
1237 for (i
= 0; i
< npath
; i
++) {
1238 PyObject
*copy
= NULL
;
1239 PyObject
*v
= PyList_GetItem(path
, i
);
1242 #ifdef Py_USING_UNICODE
1243 if (PyUnicode_Check(v
)) {
1244 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1245 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1252 if (!PyString_Check(v
))
1254 len
= PyString_GET_SIZE(v
);
1255 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1257 continue; /* Too long */
1259 strcpy(buf
, PyString_AS_STRING(v
));
1260 if (strlen(buf
) != len
) {
1262 continue; /* v contains '\0' */
1265 /* sys.path_hooks import hook */
1266 if (p_loader
!= NULL
) {
1269 importer
= get_path_importer(path_importer_cache
,
1271 if (importer
== NULL
) {
1275 /* Note: importer is a borrowed reference */
1276 if (importer
!= Py_None
) {
1278 loader
= PyObject_CallMethod(importer
,
1283 return NULL
; /* error */
1284 if (loader
!= Py_None
) {
1285 /* a loader was found */
1287 return &importhookdescr
;
1293 /* no hook was found, use builtin import */
1295 if (len
> 0 && buf
[len
-1] != SEP
1297 && buf
[len
-1] != ALTSEP
1301 strcpy(buf
+len
, name
);
1304 /* Check for package import (buf holds a directory name,
1305 and there's an __init__ module in that directory */
1307 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1308 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1309 case_ok(buf
, len
, namelen
, name
)) { /* case matches */
1310 if (find_init_module(buf
)) { /* and has __init__.py */
1315 char warnstr
[MAXPATHLEN
+80];
1316 sprintf(warnstr
, "Not importing directory "
1317 "'%.*s': missing __init__.py",
1319 if (PyErr_Warn(PyExc_ImportWarning
,
1327 /* XXX How are you going to test for directories? */
1330 case_ok(buf
, len
, namelen
, name
)) {
1331 if (find_init_module(buf
)) {
1336 char warnstr
[MAXPATHLEN
+80];
1337 sprintf(warnstr
, "Not importing directory "
1338 "'%.*s': missing __init__.py",
1340 if (PyErr_Warn(PyExc_ImportWarning
,
1348 #if defined(PYOS_OS2)
1349 /* take a snapshot of the module spec for restoration
1350 * after the 8 character DLL hackery
1352 saved_buf
= strdup(buf
);
1354 saved_namelen
= namelen
;
1355 #endif /* PYOS_OS2 */
1356 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1357 #if defined(PYOS_OS2)
1358 /* OS/2 limits DLLs to 8 character names (w/o
1360 * so if the name is longer than that and its a
1361 * dynamically loaded module we're going to try,
1362 * truncate the name before trying
1364 if (strlen(subname
) > 8) {
1365 /* is this an attempt to load a C extension? */
1366 const struct filedescr
*scan
;
1367 scan
= _PyImport_DynLoadFiletab
;
1368 while (scan
->suffix
!= NULL
) {
1369 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1374 if (scan
->suffix
!= NULL
) {
1375 /* yes, so truncate the name */
1377 len
-= strlen(subname
) - namelen
;
1381 #endif /* PYOS_OS2 */
1382 strcpy(buf
+len
, fdp
->suffix
);
1383 if (Py_VerboseFlag
> 1)
1384 PySys_WriteStderr("# trying %s\n", buf
);
1385 filemode
= fdp
->mode
;
1386 if (filemode
[0] == 'U')
1387 filemode
= "r" PY_STDIOTEXTMODE
;
1388 fp
= fopen(buf
, filemode
);
1390 if (case_ok(buf
, len
, namelen
, name
))
1392 else { /* continue search */
1397 #if defined(PYOS_OS2)
1398 /* restore the saved snapshot */
1399 strcpy(buf
, saved_buf
);
1401 namelen
= saved_namelen
;
1404 #if defined(PYOS_OS2)
1405 /* don't need/want the module name snapshot anymore */
1417 PyErr_Format(PyExc_ImportError
,
1418 "No module named %.200s", name
);
1425 /* Helpers for main.c
1426 * Find the source file corresponding to a named module
1429 _PyImport_FindModule(const char *name
, PyObject
*path
, char *buf
,
1430 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1432 return find_module((char *) name
, (char *) name
, path
,
1433 buf
, buflen
, p_fp
, p_loader
);
1436 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr
* fd
)
1438 return fd
->type
== PY_SOURCE
|| fd
->type
== PY_COMPILED
;
1441 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1442 * The arguments here are tricky, best shown by example:
1443 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1445 * |--------------------- buf ---------------------|
1446 * |------------------- len ------------------|
1447 * |------ name -------|
1448 * |----- namelen -----|
1449 * buf is the full path, but len only counts up to (& exclusive of) the
1450 * extension. name is the module name, also exclusive of extension.
1452 * We've already done a successful stat() or fopen() on buf, so know that
1453 * there's some match, possibly case-insensitive.
1455 * case_ok() is to return 1 if there's a case-sensitive match for
1456 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1459 * case_ok() is used to implement case-sensitive import semantics even
1460 * on platforms with case-insensitive filesystems. It's trivial to implement
1461 * for case-sensitive filesystems. It's pretty much a cross-platform
1462 * nightmare for systems with case-insensitive filesystems.
1465 /* First we may need a pile of platform-specific header files; the sequence
1466 * of #if's here should match the sequence in the body of case_ok().
1468 #if defined(MS_WINDOWS)
1469 #include <windows.h>
1471 #elif defined(DJGPP)
1474 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1475 #include <sys/types.h>
1478 #elif defined(PYOS_OS2)
1480 #define INCL_DOSERRORS
1481 #define INCL_NOPMAPI
1484 #elif defined(RISCOS)
1485 #include "oslib/osfscontrol.h"
1489 case_ok(char *buf
, Py_ssize_t len
, Py_ssize_t namelen
, char *name
)
1491 /* Pick a platform-specific implementation; the sequence of #if's here should
1492 * match the sequence just above.
1496 #if defined(MS_WINDOWS)
1497 WIN32_FIND_DATA data
;
1500 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1503 h
= FindFirstFile(buf
, &data
);
1504 if (h
== INVALID_HANDLE_VALUE
) {
1505 PyErr_Format(PyExc_NameError
,
1506 "Can't find file for module %.100s\n(filename %.300s)",
1511 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1514 #elif defined(DJGPP)
1518 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1521 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1523 PyErr_Format(PyExc_NameError
,
1524 "Can't find file for module %.100s\n(filename %.300s)",
1528 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1530 /* new-fangled macintosh (macosx) or Cygwin */
1531 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1534 char dirname
[MAXPATHLEN
+ 1];
1535 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1537 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1540 /* Copy the dir component into dirname; substitute "." if empty */
1546 assert(dirlen
<= MAXPATHLEN
);
1547 memcpy(dirname
, buf
, dirlen
);
1548 dirname
[dirlen
] = '\0';
1550 /* Open the directory and search the entries for an exact match. */
1551 dirp
= opendir(dirname
);
1553 char *nameWithExt
= buf
+ len
- namelen
;
1554 while ((dp
= readdir(dirp
)) != NULL
) {
1556 #ifdef _DIRENT_HAVE_D_NAMELEN
1561 if (thislen
>= namelen
&&
1562 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1563 (void)closedir(dirp
);
1564 return 1; /* Found */
1567 (void)closedir(dirp
);
1569 return 0 ; /* Not found */
1572 #elif defined(RISCOS)
1573 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1574 char buf2
[MAXPATHLEN
+2];
1575 char *nameWithExt
= buf
+len
-namelen
;
1579 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1583 append wildcard, otherwise case of filename wouldn't be touched */
1587 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1588 canonlen
= MAXPATHLEN
+1-canonlen
;
1589 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1591 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1592 return 1; /* match */
1597 #elif defined(PYOS_OS2)
1603 if (getenv("PYTHONCASEOK") != NULL
)
1606 rc
= DosFindFirst(buf
,
1608 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1609 &ffbuf
, sizeof(ffbuf
),
1614 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1616 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1625 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1627 find_init_module(char *buf
)
1629 const size_t save_len
= strlen(buf
);
1630 size_t i
= save_len
;
1631 char *pname
; /* pointer to start of __init__ */
1632 struct stat statbuf
;
1634 /* For calling case_ok(buf, len, namelen, name):
1635 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1637 * |--------------------- buf ---------------------|
1638 * |------------------- len ------------------|
1639 * |------ name -------|
1640 * |----- namelen -----|
1642 if (save_len
+ 13 >= MAXPATHLEN
)
1646 strcpy(pname
, "__init__.py");
1647 if (stat(buf
, &statbuf
) == 0) {
1649 save_len
+ 9, /* len("/__init__") */
1650 8, /* len("__init__") */
1652 buf
[save_len
] = '\0';
1657 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1658 if (stat(buf
, &statbuf
) == 0) {
1660 save_len
+ 9, /* len("/__init__") */
1661 8, /* len("__init__") */
1663 buf
[save_len
] = '\0';
1667 buf
[save_len
] = '\0';
1675 find_init_module(buf
)
1678 int save_len
= strlen(buf
);
1681 if (save_len
+ 13 >= MAXPATHLEN
)
1684 strcpy(buf
+i
, "__init__/py");
1686 buf
[save_len
] = '\0';
1690 if (Py_OptimizeFlag
)
1695 buf
[save_len
] = '\0';
1698 buf
[save_len
] = '\0';
1703 #endif /* HAVE_STAT */
1706 static int init_builtin(char *); /* Forward */
1708 /* Load an external module using the default search path and return
1709 its module object WITH INCREMENTED REFERENCE COUNT */
1712 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1718 /* First check that there's an open file (if we need one) */
1723 PyErr_Format(PyExc_ValueError
,
1724 "file object required for import (type code %d)",
1733 m
= load_source_module(name
, buf
, fp
);
1737 m
= load_compiled_module(name
, buf
, fp
);
1740 #ifdef HAVE_DYNAMIC_LOADING
1742 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1747 m
= load_package(name
, buf
);
1752 if (buf
!= NULL
&& buf
[0] != '\0')
1754 if (type
== C_BUILTIN
)
1755 err
= init_builtin(name
);
1757 err
= PyImport_ImportFrozenModule(name
);
1761 PyErr_Format(PyExc_ImportError
,
1762 "Purported %s module %.200s not found",
1764 "builtin" : "frozen",
1768 modules
= PyImport_GetModuleDict();
1769 m
= PyDict_GetItemString(modules
, name
);
1773 "%s module %.200s not properly initialized",
1775 "builtin" : "frozen",
1783 if (loader
== NULL
) {
1784 PyErr_SetString(PyExc_ImportError
,
1785 "import hook without loader");
1788 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1793 PyErr_Format(PyExc_ImportError
,
1794 "Don't know how to import %.200s (type code %d)",
1804 /* Initialize a built-in module.
1805 Return 1 for success, 0 if the module is not found, and -1 with
1806 an exception set if the initialization failed. */
1809 init_builtin(char *name
)
1813 if (_PyImport_FindExtension(name
, name
) != NULL
)
1816 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1817 if (strcmp(name
, p
->name
) == 0) {
1818 if (p
->initfunc
== NULL
) {
1819 PyErr_Format(PyExc_ImportError
,
1820 "Cannot re-init internal module %.200s",
1825 PySys_WriteStderr("import %s # builtin\n", name
);
1827 if (PyErr_Occurred())
1829 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1838 /* Frozen modules */
1840 static struct _frozen
*
1841 find_frozen(char *name
)
1845 for (p
= PyImport_FrozenModules
; ; p
++) {
1846 if (p
->name
== NULL
)
1848 if (strcmp(p
->name
, name
) == 0)
1855 get_frozen_object(char *name
)
1857 struct _frozen
*p
= find_frozen(name
);
1861 PyErr_Format(PyExc_ImportError
,
1862 "No such frozen object named %.200s",
1866 if (p
->code
== NULL
) {
1867 PyErr_Format(PyExc_ImportError
,
1868 "Excluded frozen object named %.200s",
1875 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1878 /* Initialize a frozen module.
1879 Return 1 for succes, 0 if the module is not found, and -1 with
1880 an exception set if the initialization failed.
1881 This function is also used from frozenmain.c */
1884 PyImport_ImportFrozenModule(char *name
)
1886 struct _frozen
*p
= find_frozen(name
);
1894 if (p
->code
== NULL
) {
1895 PyErr_Format(PyExc_ImportError
,
1896 "Excluded frozen object named %.200s",
1901 ispackage
= (size
< 0);
1905 PySys_WriteStderr("import %s # frozen%s\n",
1906 name
, ispackage
? " package" : "");
1907 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1910 if (!PyCode_Check(co
)) {
1911 PyErr_Format(PyExc_TypeError
,
1912 "frozen object %.200s is not a code object",
1917 /* Set __path__ to the package name */
1920 m
= PyImport_AddModule(name
);
1923 d
= PyModule_GetDict(m
);
1924 s
= PyString_InternFromString(name
);
1927 err
= PyDict_SetItemString(d
, "__path__", s
);
1932 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1944 /* Import a module, either built-in, frozen, or external, and return
1945 its module object WITH INCREMENTED REFERENCE COUNT */
1948 PyImport_ImportModule(const char *name
)
1953 pname
= PyString_FromString(name
);
1956 result
= PyImport_Import(pname
);
1961 /* Forward declarations for helper routines */
1962 static PyObject
*get_parent(PyObject
*globals
, char *buf
,
1963 Py_ssize_t
*p_buflen
, int level
);
1964 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1965 char **p_name
, char *buf
, Py_ssize_t
*p_buflen
);
1966 static int mark_miss(char *name
);
1967 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1968 char *buf
, Py_ssize_t buflen
, int recursive
);
1969 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1971 /* The Magnum Opus of dotted-name import :-) */
1974 import_module_level(char *name
, PyObject
*globals
, PyObject
*locals
,
1975 PyObject
*fromlist
, int level
)
1977 char buf
[MAXPATHLEN
+1];
1978 Py_ssize_t buflen
= 0;
1979 PyObject
*parent
, *head
, *next
, *tail
;
1981 parent
= get_parent(globals
, buf
, &buflen
, level
);
1985 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1992 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
2000 if (tail
== Py_None
) {
2001 /* If tail is Py_None, both get_parent and load_next found
2002 an empty module name: someone called __import__("") or
2003 doctored faulty bytecode */
2006 PyErr_SetString(PyExc_ValueError
,
2007 "Empty module name");
2011 if (fromlist
!= NULL
) {
2012 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
2016 if (fromlist
== NULL
) {
2022 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
2030 /* For DLL compatibility */
2031 #undef PyImport_ImportModuleEx
2033 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
2038 result
= import_module_level(name
, globals
, locals
, fromlist
, -1);
2039 if (unlock_import() < 0) {
2041 PyErr_SetString(PyExc_RuntimeError
,
2042 "not holding the import lock");
2047 #define PyImport_ImportModuleEx(n, g, l, f) \
2048 PyImport_ImportModuleLevel(n, g, l, f, -1);
2051 PyImport_ImportModuleLevel(char *name
, PyObject
*globals
, PyObject
*locals
,
2052 PyObject
*fromlist
, int level
)
2056 result
= import_module_level(name
, globals
, locals
, fromlist
, level
);
2057 if (unlock_import() < 0) {
2059 PyErr_SetString(PyExc_RuntimeError
,
2060 "not holding the import lock");
2066 /* Return the package that an import is being performed in. If globals comes
2067 from the module foo.bar.bat (not itself a package), this returns the
2068 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2069 the package's entry in sys.modules is returned, as a borrowed reference.
2071 The *name* of the returned package is returned in buf, with the length of
2072 the name in *p_buflen.
2074 If globals doesn't come from a package or a module in a package, or a
2075 corresponding entry is not found in sys.modules, Py_None is returned.
2078 get_parent(PyObject
*globals
, char *buf
, Py_ssize_t
*p_buflen
, int level
)
2080 static PyObject
*namestr
= NULL
;
2081 static PyObject
*pathstr
= NULL
;
2082 PyObject
*modname
, *modpath
, *modules
, *parent
;
2084 if (globals
== NULL
|| !PyDict_Check(globals
) || !level
)
2087 if (namestr
== NULL
) {
2088 namestr
= PyString_InternFromString("__name__");
2089 if (namestr
== NULL
)
2092 if (pathstr
== NULL
) {
2093 pathstr
= PyString_InternFromString("__path__");
2094 if (pathstr
== NULL
)
2100 modname
= PyDict_GetItem(globals
, namestr
);
2101 if (modname
== NULL
|| !PyString_Check(modname
))
2104 modpath
= PyDict_GetItem(globals
, pathstr
);
2105 if (modpath
!= NULL
) {
2106 Py_ssize_t len
= PyString_GET_SIZE(modname
);
2107 if (len
> MAXPATHLEN
) {
2108 PyErr_SetString(PyExc_ValueError
,
2109 "Module name too long");
2112 strcpy(buf
, PyString_AS_STRING(modname
));
2115 char *start
= PyString_AS_STRING(modname
);
2116 char *lastdot
= strrchr(start
, '.');
2118 if (lastdot
== NULL
&& level
> 0) {
2119 PyErr_SetString(PyExc_ValueError
,
2120 "Attempted relative import in non-package");
2123 if (lastdot
== NULL
)
2125 len
= lastdot
- start
;
2126 if (len
>= MAXPATHLEN
) {
2127 PyErr_SetString(PyExc_ValueError
,
2128 "Module name too long");
2131 strncpy(buf
, start
, len
);
2135 while (--level
> 0) {
2136 char *dot
= strrchr(buf
, '.');
2138 PyErr_SetString(PyExc_ValueError
,
2139 "Attempted relative import beyond "
2140 "toplevel package");
2145 *p_buflen
= strlen(buf
);
2147 modules
= PyImport_GetModuleDict();
2148 parent
= PyDict_GetItemString(modules
, buf
);
2150 PyErr_Format(PyExc_SystemError
,
2151 "Parent module '%.200s' not loaded", buf
);
2153 /* We expect, but can't guarantee, if parent != None, that:
2154 - parent.__name__ == buf
2155 - parent.__dict__ is globals
2156 If this is violated... Who cares? */
2159 /* altmod is either None or same as mod */
2161 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2162 Py_ssize_t
*p_buflen
)
2164 char *name
= *p_name
;
2165 char *dot
= strchr(name
, '.');
2170 if (strlen(name
) == 0) {
2171 /* completely empty module name should only happen in
2172 'from . import' (or '__import__("")')*/
2187 PyErr_SetString(PyExc_ValueError
,
2188 "Empty module name");
2192 p
= buf
+ *p_buflen
;
2195 if (p
+len
-buf
>= MAXPATHLEN
) {
2196 PyErr_SetString(PyExc_ValueError
,
2197 "Module name too long");
2200 strncpy(p
, name
, len
);
2202 *p_buflen
= p
+len
-buf
;
2204 result
= import_submodule(mod
, p
, buf
);
2205 if (result
== Py_None
&& altmod
!= mod
) {
2207 /* Here, altmod must be None and mod must not be None */
2208 result
= import_submodule(altmod
, p
, p
);
2209 if (result
!= NULL
&& result
!= Py_None
) {
2210 if (mark_miss(buf
) != 0) {
2214 strncpy(buf
, name
, len
);
2222 if (result
== Py_None
) {
2224 PyErr_Format(PyExc_ImportError
,
2225 "No module named %.200s", name
);
2233 mark_miss(char *name
)
2235 PyObject
*modules
= PyImport_GetModuleDict();
2236 return PyDict_SetItemString(modules
, name
, Py_None
);
2240 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, Py_ssize_t buflen
,
2245 if (!PyObject_HasAttrString(mod
, "__path__"))
2248 for (i
= 0; ; i
++) {
2249 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2252 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2258 if (!PyString_Check(item
)) {
2259 PyErr_SetString(PyExc_TypeError
,
2260 "Item in ``from list'' not a string");
2264 if (PyString_AS_STRING(item
)[0] == '*') {
2267 /* See if the package defines __all__ */
2269 continue; /* Avoid endless recursion */
2270 all
= PyObject_GetAttrString(mod
, "__all__");
2274 int ret
= ensure_fromlist(mod
, all
, buf
, buflen
, 1);
2281 hasit
= PyObject_HasAttr(mod
, item
);
2283 char *subname
= PyString_AS_STRING(item
);
2286 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2287 PyErr_SetString(PyExc_ValueError
,
2288 "Module name too long");
2295 submod
= import_submodule(mod
, subname
, buf
);
2297 if (submod
== NULL
) {
2309 add_submodule(PyObject
*mod
, PyObject
*submod
, char *fullname
, char *subname
,
2314 /* Irrespective of the success of this load, make a
2315 reference to it in the parent package module. A copy gets
2316 saved in the modules dictionary under the full name, so get a
2317 reference from there, if need be. (The exception is when the
2318 load failed with a SyntaxError -- then there's no trace in
2319 sys.modules. In that case, of course, do nothing extra.) */
2320 if (submod
== NULL
) {
2321 submod
= PyDict_GetItemString(modules
, fullname
);
2325 if (PyModule_Check(mod
)) {
2326 /* We can't use setattr here since it can give a
2327 * spurious warning if the submodule name shadows a
2329 PyObject
*dict
= PyModule_GetDict(mod
);
2332 if (PyDict_SetItemString(dict
, subname
, submod
) < 0)
2336 if (PyObject_SetAttrString(mod
, subname
, submod
) < 0)
2343 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2345 PyObject
*modules
= PyImport_GetModuleDict();
2349 if mod == None: subname == fullname
2350 else: mod.__name__ + "." + subname == fullname
2353 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2357 PyObject
*path
, *loader
= NULL
;
2358 char buf
[MAXPATHLEN
+1];
2359 struct filedescr
*fdp
;
2365 path
= PyObject_GetAttrString(mod
, "__path__");
2374 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2378 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2384 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2388 if (!add_submodule(mod
, m
, fullname
, subname
, modules
)) {
2398 /* Re-import a module of any kind and return its module object, WITH
2399 INCREMENTED REFERENCE COUNT */
2402 PyImport_ReloadModule(PyObject
*m
)
2404 PyObject
*modules
= PyImport_GetModuleDict();
2405 PyObject
*path
= NULL
, *loader
= NULL
;
2406 char *name
, *subname
;
2407 char buf
[MAXPATHLEN
+1];
2408 struct filedescr
*fdp
;
2412 if (m
== NULL
|| !PyModule_Check(m
)) {
2413 PyErr_SetString(PyExc_TypeError
,
2414 "reload() argument must be module");
2417 name
= PyModule_GetName(m
);
2420 if (m
!= PyDict_GetItemString(modules
, name
)) {
2421 PyErr_Format(PyExc_ImportError
,
2422 "reload(): module %.200s not in sys.modules",
2426 subname
= strrchr(name
, '.');
2427 if (subname
== NULL
)
2430 PyObject
*parentname
, *parent
;
2431 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2432 if (parentname
== NULL
)
2434 parent
= PyDict_GetItem(modules
, parentname
);
2435 if (parent
== NULL
) {
2436 PyErr_Format(PyExc_ImportError
,
2437 "reload(): parent %.200s not in sys.modules",
2438 PyString_AS_STRING(parentname
));
2439 Py_DECREF(parentname
);
2442 Py_DECREF(parentname
);
2444 path
= PyObject_GetAttrString(parent
, "__path__");
2449 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, &loader
);
2457 newm
= load_module(name
, fp
, buf
, fdp
->type
, loader
);
2463 /* load_module probably removed name from modules because of
2464 * the error. Put back the original module object. We're
2465 * going to return NULL in this case regardless of whether
2466 * replacing name succeeds, so the return value is ignored.
2468 PyDict_SetItemString(modules
, name
, m
);
2474 /* Higher-level import emulator which emulates the "import" statement
2475 more accurately -- it invokes the __import__() function from the
2476 builtins of the current globals. This means that the import is
2477 done using whatever import hooks are installed in the current
2478 environment, e.g. by "rexec".
2479 A dummy list ["__doc__"] is passed as the 4th argument so that
2480 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2481 will return <module "gencache"> instead of <module "win32com">. */
2484 PyImport_Import(PyObject
*module_name
)
2486 static PyObject
*silly_list
= NULL
;
2487 static PyObject
*builtins_str
= NULL
;
2488 static PyObject
*import_str
= NULL
;
2489 PyObject
*globals
= NULL
;
2490 PyObject
*import
= NULL
;
2491 PyObject
*builtins
= NULL
;
2494 /* Initialize constant string objects */
2495 if (silly_list
== NULL
) {
2496 import_str
= PyString_InternFromString("__import__");
2497 if (import_str
== NULL
)
2499 builtins_str
= PyString_InternFromString("__builtins__");
2500 if (builtins_str
== NULL
)
2502 silly_list
= Py_BuildValue("[s]", "__doc__");
2503 if (silly_list
== NULL
)
2507 /* Get the builtins from current globals */
2508 globals
= PyEval_GetGlobals();
2509 if (globals
!= NULL
) {
2511 builtins
= PyObject_GetItem(globals
, builtins_str
);
2512 if (builtins
== NULL
)
2516 /* No globals -- use standard builtins, and fake globals */
2519 builtins
= PyImport_ImportModuleLevel("__builtin__",
2520 NULL
, NULL
, NULL
, 0);
2521 if (builtins
== NULL
)
2523 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2524 if (globals
== NULL
)
2528 /* Get the __import__ function from the builtins */
2529 if (PyDict_Check(builtins
)) {
2530 import
= PyObject_GetItem(builtins
, import_str
);
2532 PyErr_SetObject(PyExc_KeyError
, import_str
);
2535 import
= PyObject_GetAttr(builtins
, import_str
);
2539 /* Call the _import__ function with the proper argument list */
2540 r
= PyObject_CallFunctionObjArgs(import
, module_name
, globals
,
2541 globals
, silly_list
, NULL
);
2544 Py_XDECREF(globals
);
2545 Py_XDECREF(builtins
);
2552 /* Module 'imp' provides Python access to the primitives used for
2557 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2561 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2562 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2563 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2564 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2566 return PyString_FromStringAndSize(buf
, 4);
2570 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2573 struct filedescr
*fdp
;
2575 list
= PyList_New(0);
2578 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2579 PyObject
*item
= Py_BuildValue("ssi",
2580 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2585 if (PyList_Append(list
, item
) < 0) {
2596 call_find_module(char *name
, PyObject
*path
)
2598 extern int fclose(FILE *);
2599 PyObject
*fob
, *ret
;
2600 struct filedescr
*fdp
;
2601 char pathname
[MAXPATHLEN
+1];
2605 if (path
== Py_None
)
2607 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2611 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2621 ret
= Py_BuildValue("Os(ssi)",
2622 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2628 imp_find_module(PyObject
*self
, PyObject
*args
)
2631 PyObject
*path
= NULL
;
2632 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2634 return call_find_module(name
, path
);
2638 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2643 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2645 ret
= init_builtin(name
);
2652 m
= PyImport_AddModule(name
);
2658 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2663 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2665 ret
= PyImport_ImportFrozenModule(name
);
2672 m
= PyImport_AddModule(name
);
2678 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2682 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2684 return get_frozen_object(name
);
2688 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2691 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2693 return PyInt_FromLong(is_builtin(name
));
2697 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2701 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2703 p
= find_frozen(name
);
2704 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2708 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2713 mode
= "r" PY_STDIOTEXTMODE
;
2714 fp
= fopen(pathname
, mode
);
2716 PyErr_SetFromErrno(PyExc_IOError
);
2719 fp
= PyFile_AsFile(fob
);
2721 PyErr_SetString(PyExc_ValueError
,
2722 "bad/closed file object");
2728 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2732 PyObject
*fob
= NULL
;
2735 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2736 &PyFile_Type
, &fob
))
2738 fp
= get_file(pathname
, fob
, "rb");
2741 m
= load_compiled_module(name
, pathname
, fp
);
2747 #ifdef HAVE_DYNAMIC_LOADING
2750 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2754 PyObject
*fob
= NULL
;
2757 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2758 &PyFile_Type
, &fob
))
2761 fp
= get_file(pathname
, fob
, "r");
2765 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2769 #endif /* HAVE_DYNAMIC_LOADING */
2772 imp_load_source(PyObject
*self
, PyObject
*args
)
2776 PyObject
*fob
= NULL
;
2779 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2780 &PyFile_Type
, &fob
))
2782 fp
= get_file(pathname
, fob
, "r");
2785 m
= load_source_module(name
, pathname
, fp
);
2792 imp_load_module(PyObject
*self
, PyObject
*args
)
2797 char *suffix
; /* Unused */
2802 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2803 &name
, &fob
, &pathname
,
2804 &suffix
, &mode
, &type
))
2807 /* Mode must start with 'r' or 'U' and must not contain '+'.
2808 Implicit in this test is the assumption that the mode
2809 may contain other modifiers like 'b' or 't'. */
2811 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2812 PyErr_Format(PyExc_ValueError
,
2813 "invalid file open mode %.200s", mode
);
2820 if (!PyFile_Check(fob
)) {
2821 PyErr_SetString(PyExc_ValueError
,
2822 "load_module arg#2 should be a file or None");
2825 fp
= get_file(pathname
, fob
, mode
);
2829 return load_module(name
, fp
, pathname
, type
, NULL
);
2833 imp_load_package(PyObject
*self
, PyObject
*args
)
2837 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2839 return load_package(name
, pathname
);
2843 imp_new_module(PyObject
*self
, PyObject
*args
)
2846 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2848 return PyModule_New(name
);
2853 PyDoc_STRVAR(doc_imp
,
2854 "This module provides the components needed to build your own\n\
2855 __import__ function. Undocumented functions are obsolete.");
2857 PyDoc_STRVAR(doc_find_module
,
2858 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2859 Search for a module. If path is omitted or None, search for a\n\
2860 built-in, frozen or special module and continue search in sys.path.\n\
2861 The module name cannot contain '.'; to search for a submodule of a\n\
2862 package, pass the submodule name and the package's __path__.");
2864 PyDoc_STRVAR(doc_load_module
,
2865 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2866 Load a module, given information returned by find_module().\n\
2867 The module name must include the full package name, if any.");
2869 PyDoc_STRVAR(doc_get_magic
,
2870 "get_magic() -> string\n\
2871 Return the magic number for .pyc or .pyo files.");
2873 PyDoc_STRVAR(doc_get_suffixes
,
2874 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2875 Return a list of (suffix, mode, type) tuples describing the files\n\
2876 that find_module() looks for.");
2878 PyDoc_STRVAR(doc_new_module
,
2879 "new_module(name) -> module\n\
2880 Create a new module. Do not enter it in sys.modules.\n\
2881 The module name must include the full package name, if any.");
2883 PyDoc_STRVAR(doc_lock_held
,
2884 "lock_held() -> boolean\n\
2885 Return True if the import lock is currently held, else False.\n\
2886 On platforms without threads, return False.");
2888 PyDoc_STRVAR(doc_acquire_lock
,
2889 "acquire_lock() -> None\n\
2890 Acquires the interpreter's import lock for the current thread.\n\
2891 This lock should be used by import hooks to ensure thread-safety\n\
2892 when importing modules.\n\
2893 On platforms without threads, this function does nothing.");
2895 PyDoc_STRVAR(doc_release_lock
,
2896 "release_lock() -> None\n\
2897 Release the interpreter's import lock.\n\
2898 On platforms without threads, this function does nothing.");
2900 static PyMethodDef imp_methods
[] = {
2901 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2902 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
2903 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
2904 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2905 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2906 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
2907 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
2908 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
2909 /* The rest are obsolete */
2910 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2911 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2912 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2913 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2914 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2915 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2916 #ifdef HAVE_DYNAMIC_LOADING
2917 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2919 {"load_package", imp_load_package
, METH_VARARGS
},
2920 {"load_source", imp_load_source
, METH_VARARGS
},
2921 {NULL
, NULL
} /* sentinel */
2925 setint(PyObject
*d
, char *name
, int value
)
2930 v
= PyInt_FromLong((long)value
);
2931 err
= PyDict_SetItemString(d
, name
, v
);
2941 NullImporter_init(NullImporter
*self
, PyObject
*args
, PyObject
*kwds
)
2945 if (!_PyArg_NoKeywords("NullImporter()", kwds
))
2948 if (!PyArg_ParseTuple(args
, "s:NullImporter",
2952 if (strlen(path
) == 0) {
2953 PyErr_SetString(PyExc_ImportError
, "empty pathname");
2957 struct stat statbuf
;
2960 rv
= stat(path
, &statbuf
);
2963 if (S_ISDIR(statbuf
.st_mode
)) {
2964 /* it's a directory */
2965 PyErr_SetString(PyExc_ImportError
,
2966 "existing directory");
2971 if (object_exists(path
)) {
2974 /* it's a directory */
2975 PyErr_SetString(PyExc_ImportError
,
2976 "existing directory");
2986 NullImporter_find_module(NullImporter
*self
, PyObject
*args
)
2991 static PyMethodDef NullImporter_methods
[] = {
2992 {"find_module", (PyCFunction
)NullImporter_find_module
, METH_VARARGS
,
2993 "Always return None"
2995 {NULL
} /* Sentinel */
2999 static PyTypeObject NullImporterType
= {
3000 PyObject_HEAD_INIT(NULL
)
3002 "imp.NullImporter", /*tp_name*/
3003 sizeof(NullImporter
), /*tp_basicsize*/
3012 0, /*tp_as_sequence*/
3013 0, /*tp_as_mapping*/
3020 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
3021 "Null importer object", /* tp_doc */
3022 0, /* tp_traverse */
3024 0, /* tp_richcompare */
3025 0, /* tp_weaklistoffset */
3027 0, /* tp_iternext */
3028 NullImporter_methods
, /* tp_methods */
3033 0, /* tp_descr_get */
3034 0, /* tp_descr_set */
3035 0, /* tp_dictoffset */
3036 (initproc
)NullImporter_init
, /* tp_init */
3038 PyType_GenericNew
/* tp_new */
3047 if (PyType_Ready(&NullImporterType
) < 0)
3050 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
3051 NULL
, PYTHON_API_VERSION
);
3054 d
= PyModule_GetDict(m
);
3058 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
3059 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
3060 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
3061 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
3062 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
3063 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
3064 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
3065 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
3066 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
3067 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
3069 Py_INCREF(&NullImporterType
);
3070 PyModule_AddObject(m
, "NullImporter", (PyObject
*)&NullImporterType
);
3076 /* API for embedding applications that want to add their own entries
3077 to the table of built-in modules. This should normally be called
3078 *before* Py_Initialize(). When the table resize fails, -1 is
3079 returned and the existing table is unchanged.
3081 After a similar function by Just van Rossum. */
3084 PyImport_ExtendInittab(struct _inittab
*newtab
)
3086 static struct _inittab
*our_copy
= NULL
;
3090 /* Count the number of entries in both tables */
3091 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
3094 return 0; /* Nothing to do */
3095 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
3098 /* Allocate new memory for the combined table */
3100 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
3104 /* Copy the tables into the new memory */
3105 if (our_copy
!= PyImport_Inittab
)
3106 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
3107 PyImport_Inittab
= our_copy
= p
;
3108 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
3113 /* Shorthand to add a single entry given a name and a function */
3116 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
3118 struct _inittab newtab
[2];
3120 memset(newtab
, '\0', sizeof newtab
);
3122 newtab
[0].name
= name
;
3123 newtab
[0].initfunc
= initfunc
;
3125 return PyImport_ExtendInittab(newtab
);