2 /* Module definition and import implementation */
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
25 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
28 /* Magic word to reject .pyc files generated by other Python versions.
29 It should change for each incompatible change to the bytecode.
31 The value of CR and LF is incorporated so if you ever read or write
32 a .pyc file in text mode the magic number will be wrong; also, the
33 Apple MPW compiler swaps their values, botching string constants.
35 The magic numbers must be spaced apart atleast 2 values, as the
36 -U interpeter flag will cause MAGIC+1 being used. They have been
37 odd numbers for some time now.
39 There were a variety of old schemes for setting the magic number.
40 The current working scheme is to increment the previous value by
56 Python 2.3a0: 62011 (!)
61 Python 2.5a0: 62081 (ast-branch)
62 Python 2.5a0: 62091 (with)
63 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
64 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
65 Python 2.5b3: 62111 (fix wrong code: x += yield)
66 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
67 storing constants that should have been removed)
68 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
69 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
72 #define MAGIC (62151 | ((long)'\r'<<16) | ((long)'\n'<<24))
74 /* Magic word as global; note that _PyImport_Init() can change the
75 value of this global to accommodate for alterations of how the
76 compiler works which are enabled by command line switches. */
77 static long pyc_magic
= MAGIC
;
79 /* See _PyImport_FixupExtension() below */
80 static PyObject
*extensions
= NULL
;
82 /* This table is defined in config.c: */
83 extern struct _inittab _PyImport_Inittab
[];
85 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
87 /* these tables define the module suffixes that Python recognizes */
88 struct filedescr
* _PyImport_Filetab
= NULL
;
91 static const struct filedescr _PyImport_StandardFiletab
[] = {
92 {"/py", "U", PY_SOURCE
},
93 {"/pyc", "rb", PY_COMPILED
},
97 static const struct filedescr _PyImport_StandardFiletab
[] = {
98 {".py", "U", PY_SOURCE
},
100 {".pyw", "U", PY_SOURCE
},
102 {".pyc", "rb", PY_COMPILED
},
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 #ifdef HAVE_DYNAMIC_LOADING
122 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
125 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
127 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
129 Py_FatalError("Can't initialize import file table.");
130 #ifdef HAVE_DYNAMIC_LOADING
131 memcpy(filetab
, _PyImport_DynLoadFiletab
,
132 countD
* sizeof(struct filedescr
));
134 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
135 countS
* sizeof(struct filedescr
));
136 filetab
[countD
+ countS
].suffix
= NULL
;
138 _PyImport_Filetab
= filetab
;
140 if (Py_OptimizeFlag
) {
141 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
142 for (; filetab
->suffix
!= NULL
; filetab
++) {
144 if (strcmp(filetab
->suffix
, ".pyc") == 0)
145 filetab
->suffix
= ".pyo";
147 if (strcmp(filetab
->suffix
, "/pyc") == 0)
148 filetab
->suffix
= "/pyo";
153 if (Py_UnicodeFlag
) {
154 /* Fix the pyc_magic so that byte compiled code created
155 using the all-Unicode method doesn't interfere with
156 code created in normal operation mode. */
157 pyc_magic
= MAGIC
+ 1;
162 _PyImportHooks_Init(void)
164 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
167 /* adding sys.path_hooks and sys.path_importer_cache, setting up
169 if (PyType_Ready(&PyNullImporter_Type
) < 0)
173 PySys_WriteStderr("# installing zipimport hook\n");
178 err
= PySys_SetObject("meta_path", v
);
185 err
= PySys_SetObject("path_importer_cache", v
);
189 path_hooks
= PyList_New(0);
190 if (path_hooks
== NULL
)
192 err
= PySys_SetObject("path_hooks", path_hooks
);
196 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
197 "path_importer_cache, or NullImporter failed"
201 zimpimport
= PyImport_ImportModule("zipimport");
202 if (zimpimport
== NULL
) {
203 PyErr_Clear(); /* No zip import module -- okay */
205 PySys_WriteStderr("# can't import zipimport\n");
208 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
210 Py_DECREF(zimpimport
);
211 if (zipimporter
== NULL
) {
212 PyErr_Clear(); /* No zipimporter object -- okay */
215 "# can't import zipimport.zipimporter\n");
218 /* sys.path_hooks.append(zipimporter) */
219 err
= PyList_Append(path_hooks
, zipimporter
);
220 Py_DECREF(zipimporter
);
225 "# installed zipimport hook\n");
228 Py_DECREF(path_hooks
);
234 Py_XDECREF(extensions
);
236 PyMem_DEL(_PyImport_Filetab
);
237 _PyImport_Filetab
= NULL
;
241 /* Locking primitives to prevent parallel imports of the same module
242 in different threads to return with a partially loaded module.
243 These calls are serialized by the global interpreter lock. */
247 #include "pythread.h"
249 static PyThread_type_lock import_lock
= 0;
250 static long import_lock_thread
= -1;
251 static int import_lock_level
= 0;
256 long me
= PyThread_get_thread_ident();
258 return; /* Too bad */
259 if (import_lock
== NULL
) {
260 import_lock
= PyThread_allocate_lock();
261 if (import_lock
== NULL
)
262 return; /* Nothing much we can do. */
264 if (import_lock_thread
== me
) {
268 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
270 PyThreadState
*tstate
= PyEval_SaveThread();
271 PyThread_acquire_lock(import_lock
, 1);
272 PyEval_RestoreThread(tstate
);
274 import_lock_thread
= me
;
275 import_lock_level
= 1;
281 long me
= PyThread_get_thread_ident();
282 if (me
== -1 || import_lock
== NULL
)
283 return 0; /* Too bad */
284 if (import_lock_thread
!= me
)
287 if (import_lock_level
== 0) {
288 import_lock_thread
= -1;
289 PyThread_release_lock(import_lock
);
294 /* This function is called from PyOS_AfterFork to ensure that newly
295 created child processes do not share locks with the parent. */
298 _PyImport_ReInitLock(void)
301 if (import_lock
!= NULL
)
302 import_lock
= PyThread_allocate_lock();
308 #define lock_import()
309 #define unlock_import() 0
314 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
317 return PyBool_FromLong(import_lock_thread
!= -1);
319 return PyBool_FromLong(0);
324 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
334 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
337 if (unlock_import() < 0) {
338 PyErr_SetString(PyExc_RuntimeError
,
339 "not holding the import lock");
348 imp_modules_reloading_clear(void)
350 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
351 if (interp
->modules_reloading
!= NULL
)
352 PyDict_Clear(interp
->modules_reloading
);
358 PyImport_GetModuleDict(void)
360 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
361 if (interp
->modules
== NULL
)
362 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
363 return interp
->modules
;
367 /* List of names to clear in sys */
368 static char* sys_deletes
[] = {
369 "path", "argv", "ps1", "ps2", "exitfunc",
370 "exc_type", "exc_value", "exc_traceback",
371 "last_type", "last_value", "last_traceback",
372 "path_hooks", "path_importer_cache", "meta_path",
374 "flags", "float_info",
378 static char* sys_files
[] = {
379 "stdin", "__stdin__",
380 "stdout", "__stdout__",
381 "stderr", "__stderr__",
386 /* Un-initialize things, as good as we can */
389 PyImport_Cleanup(void)
391 Py_ssize_t pos
, ndone
;
393 PyObject
*key
, *value
, *dict
;
394 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
395 PyObject
*modules
= interp
->modules
;
398 return; /* Already done */
400 /* Delete some special variables first. These are common
401 places where user values hide and people complain when their
402 destructors fail. Since the modules containing them are
403 deleted *last* of all, they would come too late in the normal
404 destruction order. Sigh. */
406 value
= PyDict_GetItemString(modules
, "__builtin__");
407 if (value
!= NULL
&& PyModule_Check(value
)) {
408 dict
= PyModule_GetDict(value
);
410 PySys_WriteStderr("# clear __builtin__._\n");
411 PyDict_SetItemString(dict
, "_", Py_None
);
413 value
= PyDict_GetItemString(modules
, "sys");
414 if (value
!= NULL
&& PyModule_Check(value
)) {
417 dict
= PyModule_GetDict(value
);
418 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
420 PySys_WriteStderr("# clear sys.%s\n", *p
);
421 PyDict_SetItemString(dict
, *p
, Py_None
);
423 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
425 PySys_WriteStderr("# restore sys.%s\n", *p
);
426 v
= PyDict_GetItemString(dict
, *(p
+1));
429 PyDict_SetItemString(dict
, *p
, v
);
433 /* First, delete __main__ */
434 value
= PyDict_GetItemString(modules
, "__main__");
435 if (value
!= NULL
&& PyModule_Check(value
)) {
437 PySys_WriteStderr("# cleanup __main__\n");
438 _PyModule_Clear(value
);
439 PyDict_SetItemString(modules
, "__main__", Py_None
);
442 /* The special treatment of __builtin__ here is because even
443 when it's not referenced as a module, its dictionary is
444 referenced by almost every module's __builtins__. Since
445 deleting a module clears its dictionary (even if there are
446 references left to it), we need to delete the __builtin__
447 module last. Likewise, we don't delete sys until the very
448 end because it is implicitly referenced (e.g. by print).
450 Also note that we 'delete' modules by replacing their entry
451 in the modules dict with None, rather than really deleting
452 them; this avoids a rehash of the modules dictionary and
453 also marks them as "non existent" so they won't be
456 /* Next, repeatedly delete modules with a reference count of
457 one (skipping __builtin__ and sys) and delete them */
461 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
462 if (value
->ob_refcnt
!= 1)
464 if (PyString_Check(key
) && PyModule_Check(value
)) {
465 name
= PyString_AS_STRING(key
);
466 if (strcmp(name
, "__builtin__") == 0)
468 if (strcmp(name
, "sys") == 0)
472 "# cleanup[1] %s\n", name
);
473 _PyModule_Clear(value
);
474 PyDict_SetItem(modules
, key
, Py_None
);
480 /* Next, delete all modules (still skipping __builtin__ and sys) */
482 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
483 if (PyString_Check(key
) && PyModule_Check(value
)) {
484 name
= PyString_AS_STRING(key
);
485 if (strcmp(name
, "__builtin__") == 0)
487 if (strcmp(name
, "sys") == 0)
490 PySys_WriteStderr("# cleanup[2] %s\n", name
);
491 _PyModule_Clear(value
);
492 PyDict_SetItem(modules
, key
, Py_None
);
496 /* Next, delete sys and __builtin__ (in that order) */
497 value
= PyDict_GetItemString(modules
, "sys");
498 if (value
!= NULL
&& PyModule_Check(value
)) {
500 PySys_WriteStderr("# cleanup sys\n");
501 _PyModule_Clear(value
);
502 PyDict_SetItemString(modules
, "sys", Py_None
);
504 value
= PyDict_GetItemString(modules
, "__builtin__");
505 if (value
!= NULL
&& PyModule_Check(value
)) {
507 PySys_WriteStderr("# cleanup __builtin__\n");
508 _PyModule_Clear(value
);
509 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
512 /* Finally, clear and delete the modules directory */
513 PyDict_Clear(modules
);
514 interp
->modules
= NULL
;
516 Py_CLEAR(interp
->modules_reloading
);
520 /* Helper for pythonrun.c -- return magic number */
523 PyImport_GetMagicNumber(void)
529 /* Magic for extension modules (built-in as well as dynamically
530 loaded). To prevent initializing an extension module more than
531 once, we keep a static dictionary 'extensions' keyed by module name
532 (for built-in modules) or by filename (for dynamically loaded
533 modules), containing these modules. A copy of the module's
534 dictionary is stored by calling _PyImport_FixupExtension()
535 immediately after the module initialization function succeeds. A
536 copy can be retrieved from there by calling
537 _PyImport_FindExtension(). */
540 _PyImport_FixupExtension(char *name
, char *filename
)
542 PyObject
*modules
, *mod
, *dict
, *copy
;
543 if (extensions
== NULL
) {
544 extensions
= PyDict_New();
545 if (extensions
== NULL
)
548 modules
= PyImport_GetModuleDict();
549 mod
= PyDict_GetItemString(modules
, name
);
550 if (mod
== NULL
|| !PyModule_Check(mod
)) {
551 PyErr_Format(PyExc_SystemError
,
552 "_PyImport_FixupExtension: module %.200s not loaded", name
);
555 dict
= PyModule_GetDict(mod
);
558 copy
= PyDict_Copy(dict
);
561 PyDict_SetItemString(extensions
, filename
, copy
);
567 _PyImport_FindExtension(char *name
, char *filename
)
569 PyObject
*dict
, *mod
, *mdict
;
570 if (extensions
== NULL
)
572 dict
= PyDict_GetItemString(extensions
, filename
);
575 mod
= PyImport_AddModule(name
);
578 mdict
= PyModule_GetDict(mod
);
581 if (PyDict_Update(mdict
, dict
))
584 PySys_WriteStderr("import %s # previously loaded (%s)\n",
590 /* Get the module object corresponding to a module name.
591 First check the modules dictionary if there's one there,
592 if not, create a new one and insert it in the modules dictionary.
593 Because the former action is most common, THIS DOES NOT RETURN A
597 PyImport_AddModule(const char *name
)
599 PyObject
*modules
= PyImport_GetModuleDict();
602 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
605 m
= PyModule_New(name
);
608 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
612 Py_DECREF(m
); /* Yes, it still exists, in modules! */
617 /* Remove name from sys.modules, if it's there. */
619 _RemoveModule(const char *name
)
621 PyObject
*modules
= PyImport_GetModuleDict();
622 if (PyDict_GetItemString(modules
, name
) == NULL
)
624 if (PyDict_DelItemString(modules
, name
) < 0)
625 Py_FatalError("import: deleting existing key in"
626 "sys.modules failed");
629 /* Execute a code object in a module and return the module object
630 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
631 * removed from sys.modules, to avoid leaving damaged module objects
632 * in sys.modules. The caller may wish to restore the original
633 * module object (if any) in this case; PyImport_ReloadModule is an
637 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
639 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
643 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
645 PyObject
*modules
= PyImport_GetModuleDict();
648 m
= PyImport_AddModule(name
);
651 /* If the module is being reloaded, we get the old module back
652 and re-use its dict to exec the new code. */
653 d
= PyModule_GetDict(m
);
654 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
655 if (PyDict_SetItemString(d
, "__builtins__",
656 PyEval_GetBuiltins()) != 0)
659 /* Remember the filename as the __file__ attribute */
661 if (pathname
!= NULL
) {
662 v
= PyString_FromString(pathname
);
667 v
= ((PyCodeObject
*)co
)->co_filename
;
670 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
671 PyErr_Clear(); /* Not important enough to report */
674 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
679 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
680 PyErr_Format(PyExc_ImportError
,
681 "Loaded module %.200s not found in sys.modules",
696 /* Given a pathname for a Python source file, fill a buffer with the
697 pathname for the corresponding compiled file. Return the pathname
698 for the compiled file, or NULL if there's no space in the buffer.
699 Doesn't set an exception. */
702 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
704 size_t len
= strlen(pathname
);
709 /* Treat .pyw as if it were .py. The case of ".pyw" must match
710 that used in _PyImport_StandardFiletab. */
711 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
712 --len
; /* pretend 'w' isn't there */
714 memcpy(buf
, pathname
, len
);
715 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
722 /* Given a pathname for a Python source file, its time of last
723 modification, and a pathname for a compiled file, check whether the
724 compiled file represents the same version of the source. If so,
725 return a FILE pointer for the compiled file, positioned just after
726 the header; if not, return NULL.
727 Doesn't set an exception. */
730 check_compiled_module(char *pathname
, time_t mtime
, char *cpathname
)
736 fp
= fopen(cpathname
, "rb");
739 magic
= PyMarshal_ReadLongFromFile(fp
);
740 if (magic
!= pyc_magic
) {
742 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
746 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
747 if (pyc_mtime
!= mtime
) {
749 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
754 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
759 /* Read a code object from a file and check it for validity */
761 static PyCodeObject
*
762 read_compiled_module(char *cpathname
, FILE *fp
)
766 co
= PyMarshal_ReadLastObjectFromFile(fp
);
769 if (!PyCode_Check(co
)) {
770 PyErr_Format(PyExc_ImportError
,
771 "Non-code object in %.200s", cpathname
);
775 return (PyCodeObject
*)co
;
779 /* Load a module from a compiled file, execute it, and return its
780 module object WITH INCREMENTED REFERENCE COUNT */
783 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
789 magic
= PyMarshal_ReadLongFromFile(fp
);
790 if (magic
!= pyc_magic
) {
791 PyErr_Format(PyExc_ImportError
,
792 "Bad magic number in %.200s", cpathname
);
795 (void) PyMarshal_ReadLongFromFile(fp
);
796 co
= read_compiled_module(cpathname
, fp
);
800 PySys_WriteStderr("import %s # precompiled from %s\n",
802 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
808 /* Parse a source file and return the corresponding code object */
810 static PyCodeObject
*
811 parse_source_module(const char *pathname
, FILE *fp
)
813 PyCodeObject
*co
= NULL
;
815 PyArena
*arena
= PyArena_New();
819 mod
= PyParser_ASTFromFile(fp
, pathname
, Py_file_input
, 0, 0, 0,
822 co
= PyAST_Compile(mod
, pathname
, NULL
, arena
);
829 /* Helper to open a bytecode file for writing in exclusive mode */
832 open_exclusive(char *filename
)
834 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
835 /* Use O_EXCL to avoid a race condition when another process tries to
836 write the same file. When that happens, our open() call fails,
837 which is just fine (since it's only a cache).
838 XXX If the file exists and is writable but the directory is not
839 writable, the file will never be written. Oh well.
842 (void) unlink(filename
);
843 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
845 |O_BINARY
/* necessary for Windows */
848 , 0666, "ctxt=bin", "shr=nil"
855 return fdopen(fd
, "wb");
857 /* Best we can do -- on Windows this can't happen anyway */
858 return fopen(filename
, "wb");
863 /* Write a compiled module to a file, placing the time of last
864 modification of its source into the header.
865 Errors are ignored, if a write error occurs an attempt is made to
869 write_compiled_module(PyCodeObject
*co
, char *cpathname
, time_t mtime
)
873 fp
= open_exclusive(cpathname
);
877 "# can't create %s\n", cpathname
);
880 PyMarshal_WriteLongToFile(pyc_magic
, fp
, Py_MARSHAL_VERSION
);
881 /* First write a 0 for mtime */
882 PyMarshal_WriteLongToFile(0L, fp
, Py_MARSHAL_VERSION
);
883 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
, Py_MARSHAL_VERSION
);
884 if (fflush(fp
) != 0 || ferror(fp
)) {
886 PySys_WriteStderr("# can't write %s\n", cpathname
);
887 /* Don't keep partial file */
889 (void) unlink(cpathname
);
892 /* Now write the true mtime */
894 assert(mtime
< LONG_MAX
);
895 PyMarshal_WriteLongToFile((long)mtime
, fp
, Py_MARSHAL_VERSION
);
899 PySys_WriteStderr("# wrote %s\n", cpathname
);
903 /* Load a source module from a given file and return its module
904 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
905 byte-compiled file, use that instead. */
908 load_source_module(char *name
, char *pathname
, FILE *fp
)
912 char buf
[MAXPATHLEN
+1];
917 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
918 if (mtime
== (time_t)(-1)) {
919 PyErr_Format(PyExc_RuntimeError
,
920 "unable to get modification time from '%s'",
924 #if SIZEOF_TIME_T > 4
925 /* Python's .pyc timestamp handling presumes that the timestamp fits
926 in 4 bytes. This will be fine until sometime in the year 2038,
927 when a 4-byte signed time_t will overflow.
930 PyErr_SetString(PyExc_OverflowError
,
931 "modification time overflows a 4 byte field");
935 cpathname
= make_compiled_pathname(pathname
, buf
,
936 (size_t)MAXPATHLEN
+ 1);
937 if (cpathname
!= NULL
&&
938 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
939 co
= read_compiled_module(cpathname
, fpc
);
944 PySys_WriteStderr("import %s # precompiled from %s\n",
946 pathname
= cpathname
;
949 co
= parse_source_module(pathname
, fp
);
953 PySys_WriteStderr("import %s # from %s\n",
956 PyObject
*ro
= PySys_GetObject("dont_write_bytecode");
957 if (ro
== NULL
|| !PyObject_IsTrue(ro
))
958 write_compiled_module(co
, cpathname
, mtime
);
961 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
969 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
970 static struct filedescr
*find_module(char *, char *, PyObject
*,
971 char *, size_t, FILE **, PyObject
**);
972 static struct _frozen
*find_frozen(char *name
);
974 /* Load a package and return its module object WITH INCREMENTED
978 load_package(char *name
, char *pathname
)
981 PyObject
*file
= NULL
;
982 PyObject
*path
= NULL
;
984 char buf
[MAXPATHLEN
+1];
986 struct filedescr
*fdp
;
988 m
= PyImport_AddModule(name
);
992 PySys_WriteStderr("import %s # directory %s\n",
994 d
= PyModule_GetDict(m
);
995 file
= PyString_FromString(pathname
);
998 path
= Py_BuildValue("[O]", file
);
1001 err
= PyDict_SetItemString(d
, "__file__", file
);
1003 err
= PyDict_SetItemString(d
, "__path__", path
);
1007 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
1009 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1017 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
1031 /* Helper to test for built-in module */
1034 is_builtin(char *name
)
1037 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
1038 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
1039 if (PyImport_Inittab
[i
].initfunc
== NULL
)
1049 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1050 possibly by fetching it from the path_importer_cache dict. If it
1051 wasn't yet cached, traverse path_hooks until a hook is found
1052 that can handle the path item. Return None if no hook could;
1053 this tells our caller it should fall back to the builtin
1054 import mechanism. Cache the result in path_importer_cache.
1055 Returns a borrowed reference. */
1058 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
1062 Py_ssize_t j
, nhooks
;
1064 /* These conditions are the caller's responsibility: */
1065 assert(PyList_Check(path_hooks
));
1066 assert(PyDict_Check(path_importer_cache
));
1068 nhooks
= PyList_Size(path_hooks
);
1070 return NULL
; /* Shouldn't happen */
1072 importer
= PyDict_GetItem(path_importer_cache
, p
);
1073 if (importer
!= NULL
)
1076 /* set path_importer_cache[p] to None to avoid recursion */
1077 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1080 for (j
= 0; j
< nhooks
; j
++) {
1081 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1084 importer
= PyObject_CallFunctionObjArgs(hook
, p
, NULL
);
1085 if (importer
!= NULL
)
1088 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1093 if (importer
== NULL
) {
1094 importer
= PyObject_CallFunctionObjArgs(
1095 (PyObject
*)&PyNullImporter_Type
, p
, NULL
1097 if (importer
== NULL
) {
1098 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1104 if (importer
!= NULL
) {
1105 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1106 Py_DECREF(importer
);
1113 PyAPI_FUNC(PyObject
*)
1114 PyImport_GetImporter(PyObject
*path
) {
1115 PyObject
*importer
=NULL
, *path_importer_cache
=NULL
, *path_hooks
=NULL
;
1117 if ((path_importer_cache
= PySys_GetObject("path_importer_cache"))) {
1118 if ((path_hooks
= PySys_GetObject("path_hooks"))) {
1119 importer
= get_path_importer(path_importer_cache
,
1123 Py_XINCREF(importer
); /* get_path_importer returns a borrowed reference */
1127 /* Search the path (default sys.path) for a module. Return the
1128 corresponding filedescr struct, and (via return arguments) the
1129 pathname and an open file. Return NULL if the module is not found. */
1132 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1133 char *, Py_ssize_t
);
1136 static int case_ok(char *, Py_ssize_t
, Py_ssize_t
, char *);
1137 static int find_init_module(char *); /* Forward */
1138 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1140 static struct filedescr
*
1141 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1142 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1144 Py_ssize_t i
, npath
;
1145 size_t len
, namelen
;
1146 struct filedescr
*fdp
= NULL
;
1149 PyObject
*path_hooks
, *path_importer_cache
;
1151 struct stat statbuf
;
1153 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1154 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1155 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1156 char name
[MAXPATHLEN
+1];
1157 #if defined(PYOS_OS2)
1159 size_t saved_namelen
;
1160 char *saved_buf
= NULL
;
1162 if (p_loader
!= NULL
)
1165 if (strlen(subname
) > MAXPATHLEN
) {
1166 PyErr_SetString(PyExc_OverflowError
,
1167 "module name is too long");
1170 strcpy(name
, subname
);
1172 /* sys.meta_path import hook */
1173 if (p_loader
!= NULL
) {
1174 PyObject
*meta_path
;
1176 meta_path
= PySys_GetObject("meta_path");
1177 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1178 PyErr_SetString(PyExc_ImportError
,
1179 "sys.meta_path must be a list of "
1183 Py_INCREF(meta_path
); /* zap guard */
1184 npath
= PyList_Size(meta_path
);
1185 for (i
= 0; i
< npath
; i
++) {
1187 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1188 loader
= PyObject_CallMethod(hook
, "find_module",
1192 if (loader
== NULL
) {
1193 Py_DECREF(meta_path
);
1194 return NULL
; /* true error */
1196 if (loader
!= Py_None
) {
1197 /* a loader was found */
1199 Py_DECREF(meta_path
);
1200 return &importhookdescr
;
1204 Py_DECREF(meta_path
);
1207 if (path
!= NULL
&& PyString_Check(path
)) {
1208 /* The only type of submodule allowed inside a "frozen"
1209 package are other frozen modules or packages. */
1210 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1211 PyErr_SetString(PyExc_ImportError
,
1212 "full frozen module name too long");
1215 strcpy(buf
, PyString_AsString(path
));
1219 if (find_frozen(name
) != NULL
) {
1223 PyErr_Format(PyExc_ImportError
,
1224 "No frozen submodule named %.200s", name
);
1228 if (is_builtin(name
)) {
1232 if ((find_frozen(name
)) != NULL
) {
1238 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1244 path
= PySys_GetObject("path");
1246 if (path
== NULL
|| !PyList_Check(path
)) {
1247 PyErr_SetString(PyExc_ImportError
,
1248 "sys.path must be a list of directory names");
1252 path_hooks
= PySys_GetObject("path_hooks");
1253 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1254 PyErr_SetString(PyExc_ImportError
,
1255 "sys.path_hooks must be a list of "
1259 path_importer_cache
= PySys_GetObject("path_importer_cache");
1260 if (path_importer_cache
== NULL
||
1261 !PyDict_Check(path_importer_cache
)) {
1262 PyErr_SetString(PyExc_ImportError
,
1263 "sys.path_importer_cache must be a dict");
1267 npath
= PyList_Size(path
);
1268 namelen
= strlen(name
);
1269 for (i
= 0; i
< npath
; i
++) {
1270 PyObject
*copy
= NULL
;
1271 PyObject
*v
= PyList_GetItem(path
, i
);
1274 #ifdef Py_USING_UNICODE
1275 if (PyUnicode_Check(v
)) {
1276 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1277 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1284 if (!PyString_Check(v
))
1286 len
= PyString_GET_SIZE(v
);
1287 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1289 continue; /* Too long */
1291 strcpy(buf
, PyString_AS_STRING(v
));
1292 if (strlen(buf
) != len
) {
1294 continue; /* v contains '\0' */
1297 /* sys.path_hooks import hook */
1298 if (p_loader
!= NULL
) {
1301 importer
= get_path_importer(path_importer_cache
,
1303 if (importer
== NULL
) {
1307 /* Note: importer is a borrowed reference */
1308 if (importer
!= Py_None
) {
1310 loader
= PyObject_CallMethod(importer
,
1315 return NULL
; /* error */
1316 if (loader
!= Py_None
) {
1317 /* a loader was found */
1319 return &importhookdescr
;
1325 /* no hook was found, use builtin import */
1327 if (len
> 0 && buf
[len
-1] != SEP
1329 && buf
[len
-1] != ALTSEP
1333 strcpy(buf
+len
, name
);
1336 /* Check for package import (buf holds a directory name,
1337 and there's an __init__ module in that directory */
1339 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1340 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1341 case_ok(buf
, len
, namelen
, name
)) { /* case matches */
1342 if (find_init_module(buf
)) { /* and has __init__.py */
1347 char warnstr
[MAXPATHLEN
+80];
1348 sprintf(warnstr
, "Not importing directory "
1349 "'%.*s': missing __init__.py",
1351 if (PyErr_Warn(PyExc_ImportWarning
,
1359 /* XXX How are you going to test for directories? */
1362 case_ok(buf
, len
, namelen
, name
)) {
1363 if (find_init_module(buf
)) {
1368 char warnstr
[MAXPATHLEN
+80];
1369 sprintf(warnstr
, "Not importing directory "
1370 "'%.*s': missing __init__.py",
1372 if (PyErr_Warn(PyExc_ImportWarning
,
1380 #if defined(PYOS_OS2)
1381 /* take a snapshot of the module spec for restoration
1382 * after the 8 character DLL hackery
1384 saved_buf
= strdup(buf
);
1386 saved_namelen
= namelen
;
1387 #endif /* PYOS_OS2 */
1388 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1389 #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
1390 /* OS/2 limits DLLs to 8 character names (w/o
1392 * so if the name is longer than that and its a
1393 * dynamically loaded module we're going to try,
1394 * truncate the name before trying
1396 if (strlen(subname
) > 8) {
1397 /* is this an attempt to load a C extension? */
1398 const struct filedescr
*scan
;
1399 scan
= _PyImport_DynLoadFiletab
;
1400 while (scan
->suffix
!= NULL
) {
1401 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1406 if (scan
->suffix
!= NULL
) {
1407 /* yes, so truncate the name */
1409 len
-= strlen(subname
) - namelen
;
1413 #endif /* PYOS_OS2 */
1414 strcpy(buf
+len
, fdp
->suffix
);
1415 if (Py_VerboseFlag
> 1)
1416 PySys_WriteStderr("# trying %s\n", buf
);
1417 filemode
= fdp
->mode
;
1418 if (filemode
[0] == 'U')
1419 filemode
= "r" PY_STDIOTEXTMODE
;
1420 fp
= fopen(buf
, filemode
);
1422 if (case_ok(buf
, len
, namelen
, name
))
1424 else { /* continue search */
1429 #if defined(PYOS_OS2)
1430 /* restore the saved snapshot */
1431 strcpy(buf
, saved_buf
);
1433 namelen
= saved_namelen
;
1436 #if defined(PYOS_OS2)
1437 /* don't need/want the module name snapshot anymore */
1449 PyErr_Format(PyExc_ImportError
,
1450 "No module named %.200s", name
);
1457 /* Helpers for main.c
1458 * Find the source file corresponding to a named module
1461 _PyImport_FindModule(const char *name
, PyObject
*path
, char *buf
,
1462 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1464 return find_module((char *) name
, (char *) name
, path
,
1465 buf
, buflen
, p_fp
, p_loader
);
1468 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr
* fd
)
1470 return fd
->type
== PY_SOURCE
|| fd
->type
== PY_COMPILED
;
1473 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1474 * The arguments here are tricky, best shown by example:
1475 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1477 * |--------------------- buf ---------------------|
1478 * |------------------- len ------------------|
1479 * |------ name -------|
1480 * |----- namelen -----|
1481 * buf is the full path, but len only counts up to (& exclusive of) the
1482 * extension. name is the module name, also exclusive of extension.
1484 * We've already done a successful stat() or fopen() on buf, so know that
1485 * there's some match, possibly case-insensitive.
1487 * case_ok() is to return 1 if there's a case-sensitive match for
1488 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1491 * case_ok() is used to implement case-sensitive import semantics even
1492 * on platforms with case-insensitive filesystems. It's trivial to implement
1493 * for case-sensitive filesystems. It's pretty much a cross-platform
1494 * nightmare for systems with case-insensitive filesystems.
1497 /* First we may need a pile of platform-specific header files; the sequence
1498 * of #if's here should match the sequence in the body of case_ok().
1500 #if defined(MS_WINDOWS)
1501 #include <windows.h>
1503 #elif defined(DJGPP)
1506 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1507 #include <sys/types.h>
1510 #elif defined(PYOS_OS2)
1512 #define INCL_DOSERRORS
1513 #define INCL_NOPMAPI
1516 #elif defined(RISCOS)
1517 #include "oslib/osfscontrol.h"
1521 case_ok(char *buf
, Py_ssize_t len
, Py_ssize_t namelen
, char *name
)
1523 /* Pick a platform-specific implementation; the sequence of #if's here should
1524 * match the sequence just above.
1528 #if defined(MS_WINDOWS)
1529 WIN32_FIND_DATA data
;
1532 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1535 h
= FindFirstFile(buf
, &data
);
1536 if (h
== INVALID_HANDLE_VALUE
) {
1537 PyErr_Format(PyExc_NameError
,
1538 "Can't find file for module %.100s\n(filename %.300s)",
1543 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1546 #elif defined(DJGPP)
1550 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1553 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1555 PyErr_Format(PyExc_NameError
,
1556 "Can't find file for module %.100s\n(filename %.300s)",
1560 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1562 /* new-fangled macintosh (macosx) or Cygwin */
1563 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1566 char dirname
[MAXPATHLEN
+ 1];
1567 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1569 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1572 /* Copy the dir component into dirname; substitute "." if empty */
1578 assert(dirlen
<= MAXPATHLEN
);
1579 memcpy(dirname
, buf
, dirlen
);
1580 dirname
[dirlen
] = '\0';
1582 /* Open the directory and search the entries for an exact match. */
1583 dirp
= opendir(dirname
);
1585 char *nameWithExt
= buf
+ len
- namelen
;
1586 while ((dp
= readdir(dirp
)) != NULL
) {
1588 #ifdef _DIRENT_HAVE_D_NAMELEN
1593 if (thislen
>= namelen
&&
1594 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1595 (void)closedir(dirp
);
1596 return 1; /* Found */
1599 (void)closedir(dirp
);
1601 return 0 ; /* Not found */
1604 #elif defined(RISCOS)
1605 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1606 char buf2
[MAXPATHLEN
+2];
1607 char *nameWithExt
= buf
+len
-namelen
;
1611 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1615 append wildcard, otherwise case of filename wouldn't be touched */
1619 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1620 canonlen
= MAXPATHLEN
+1-canonlen
;
1621 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1623 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1624 return 1; /* match */
1629 #elif defined(PYOS_OS2)
1635 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1638 rc
= DosFindFirst(buf
,
1640 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1641 &ffbuf
, sizeof(ffbuf
),
1646 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1648 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1657 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1659 find_init_module(char *buf
)
1661 const size_t save_len
= strlen(buf
);
1662 size_t i
= save_len
;
1663 char *pname
; /* pointer to start of __init__ */
1664 struct stat statbuf
;
1666 /* For calling case_ok(buf, len, namelen, name):
1667 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1669 * |--------------------- buf ---------------------|
1670 * |------------------- len ------------------|
1671 * |------ name -------|
1672 * |----- namelen -----|
1674 if (save_len
+ 13 >= MAXPATHLEN
)
1678 strcpy(pname
, "__init__.py");
1679 if (stat(buf
, &statbuf
) == 0) {
1681 save_len
+ 9, /* len("/__init__") */
1682 8, /* len("__init__") */
1684 buf
[save_len
] = '\0';
1689 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1690 if (stat(buf
, &statbuf
) == 0) {
1692 save_len
+ 9, /* len("/__init__") */
1693 8, /* len("__init__") */
1695 buf
[save_len
] = '\0';
1699 buf
[save_len
] = '\0';
1707 find_init_module(buf
)
1710 int save_len
= strlen(buf
);
1713 if (save_len
+ 13 >= MAXPATHLEN
)
1716 strcpy(buf
+i
, "__init__/py");
1718 buf
[save_len
] = '\0';
1722 if (Py_OptimizeFlag
)
1727 buf
[save_len
] = '\0';
1730 buf
[save_len
] = '\0';
1735 #endif /* HAVE_STAT */
1738 static int init_builtin(char *); /* Forward */
1740 /* Load an external module using the default search path and return
1741 its module object WITH INCREMENTED REFERENCE COUNT */
1744 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1750 /* First check that there's an open file (if we need one) */
1755 PyErr_Format(PyExc_ValueError
,
1756 "file object required for import (type code %d)",
1765 m
= load_source_module(name
, buf
, fp
);
1769 m
= load_compiled_module(name
, buf
, fp
);
1772 #ifdef HAVE_DYNAMIC_LOADING
1774 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1779 m
= load_package(name
, buf
);
1784 if (buf
!= NULL
&& buf
[0] != '\0')
1786 if (type
== C_BUILTIN
)
1787 err
= init_builtin(name
);
1789 err
= PyImport_ImportFrozenModule(name
);
1793 PyErr_Format(PyExc_ImportError
,
1794 "Purported %s module %.200s not found",
1796 "builtin" : "frozen",
1800 modules
= PyImport_GetModuleDict();
1801 m
= PyDict_GetItemString(modules
, name
);
1805 "%s module %.200s not properly initialized",
1807 "builtin" : "frozen",
1815 if (loader
== NULL
) {
1816 PyErr_SetString(PyExc_ImportError
,
1817 "import hook without loader");
1820 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1825 PyErr_Format(PyExc_ImportError
,
1826 "Don't know how to import %.200s (type code %d)",
1836 /* Initialize a built-in module.
1837 Return 1 for success, 0 if the module is not found, and -1 with
1838 an exception set if the initialization failed. */
1841 init_builtin(char *name
)
1845 if (_PyImport_FindExtension(name
, name
) != NULL
)
1848 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1849 if (strcmp(name
, p
->name
) == 0) {
1850 if (p
->initfunc
== NULL
) {
1851 PyErr_Format(PyExc_ImportError
,
1852 "Cannot re-init internal module %.200s",
1857 PySys_WriteStderr("import %s # builtin\n", name
);
1859 if (PyErr_Occurred())
1861 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1870 /* Frozen modules */
1872 static struct _frozen
*
1873 find_frozen(char *name
)
1877 for (p
= PyImport_FrozenModules
; ; p
++) {
1878 if (p
->name
== NULL
)
1880 if (strcmp(p
->name
, name
) == 0)
1887 get_frozen_object(char *name
)
1889 struct _frozen
*p
= find_frozen(name
);
1893 PyErr_Format(PyExc_ImportError
,
1894 "No such frozen object named %.200s",
1898 if (p
->code
== NULL
) {
1899 PyErr_Format(PyExc_ImportError
,
1900 "Excluded frozen object named %.200s",
1907 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1910 /* Initialize a frozen module.
1911 Return 1 for succes, 0 if the module is not found, and -1 with
1912 an exception set if the initialization failed.
1913 This function is also used from frozenmain.c */
1916 PyImport_ImportFrozenModule(char *name
)
1918 struct _frozen
*p
= find_frozen(name
);
1926 if (p
->code
== NULL
) {
1927 PyErr_Format(PyExc_ImportError
,
1928 "Excluded frozen object named %.200s",
1933 ispackage
= (size
< 0);
1937 PySys_WriteStderr("import %s # frozen%s\n",
1938 name
, ispackage
? " package" : "");
1939 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1942 if (!PyCode_Check(co
)) {
1943 PyErr_Format(PyExc_TypeError
,
1944 "frozen object %.200s is not a code object",
1949 /* Set __path__ to the package name */
1952 m
= PyImport_AddModule(name
);
1955 d
= PyModule_GetDict(m
);
1956 s
= PyString_InternFromString(name
);
1959 err
= PyDict_SetItemString(d
, "__path__", s
);
1964 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1976 /* Import a module, either built-in, frozen, or external, and return
1977 its module object WITH INCREMENTED REFERENCE COUNT */
1980 PyImport_ImportModule(const char *name
)
1985 pname
= PyString_FromString(name
);
1988 result
= PyImport_Import(pname
);
1993 /* Import a module without blocking
1995 * At first it tries to fetch the module from sys.modules. If the module was
1996 * never loaded before it loads it with PyImport_ImportModule() unless another
1997 * thread holds the import lock. In the latter case the function raises an
1998 * ImportError instead of blocking.
2000 * Returns the module object with incremented ref count.
2003 PyImport_ImportModuleNoBlock(const char *name
)
2009 /* Try to get the module from sys.modules[name] */
2010 modules
= PyImport_GetModuleDict();
2011 if (modules
== NULL
)
2014 result
= PyDict_GetItemString(modules
, name
);
2015 if (result
!= NULL
) {
2023 /* check the import lock
2024 * me might be -1 but I ignore the error here, the lock function
2025 * takes care of the problem */
2026 me
= PyThread_get_thread_ident();
2027 if (import_lock_thread
== -1 || import_lock_thread
== me
) {
2028 /* no thread or me is holding the lock */
2029 return PyImport_ImportModule(name
);
2032 PyErr_Format(PyExc_ImportError
,
2033 "Failed to import %.200s because the import lock"
2034 "is held by another thread.",
2040 /* Forward declarations for helper routines */
2041 static PyObject
*get_parent(PyObject
*globals
, char *buf
,
2042 Py_ssize_t
*p_buflen
, int level
);
2043 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
2044 char **p_name
, char *buf
, Py_ssize_t
*p_buflen
);
2045 static int mark_miss(char *name
);
2046 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
2047 char *buf
, Py_ssize_t buflen
, int recursive
);
2048 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
2050 /* The Magnum Opus of dotted-name import :-) */
2053 import_module_level(char *name
, PyObject
*globals
, PyObject
*locals
,
2054 PyObject
*fromlist
, int level
)
2056 char buf
[MAXPATHLEN
+1];
2057 Py_ssize_t buflen
= 0;
2058 PyObject
*parent
, *head
, *next
, *tail
;
2060 if (strchr(name
, '/') != NULL
2062 || strchr(name
, '\\') != NULL
2065 PyErr_SetString(PyExc_ImportError
,
2066 "Import by filename is not supported.");
2070 parent
= get_parent(globals
, buf
, &buflen
, level
);
2074 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
2081 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
2089 if (tail
== Py_None
) {
2090 /* If tail is Py_None, both get_parent and load_next found
2091 an empty module name: someone called __import__("") or
2092 doctored faulty bytecode */
2095 PyErr_SetString(PyExc_ValueError
,
2096 "Empty module name");
2100 if (fromlist
!= NULL
) {
2101 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
2105 if (fromlist
== NULL
) {
2111 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
2120 PyImport_ImportModuleLevel(char *name
, PyObject
*globals
, PyObject
*locals
,
2121 PyObject
*fromlist
, int level
)
2125 result
= import_module_level(name
, globals
, locals
, fromlist
, level
);
2126 if (unlock_import() < 0) {
2128 PyErr_SetString(PyExc_RuntimeError
,
2129 "not holding the import lock");
2135 /* Return the package that an import is being performed in. If globals comes
2136 from the module foo.bar.bat (not itself a package), this returns the
2137 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2138 the package's entry in sys.modules is returned, as a borrowed reference.
2140 The *name* of the returned package is returned in buf, with the length of
2141 the name in *p_buflen.
2143 If globals doesn't come from a package or a module in a package, or a
2144 corresponding entry is not found in sys.modules, Py_None is returned.
2147 get_parent(PyObject
*globals
, char *buf
, Py_ssize_t
*p_buflen
, int level
)
2149 static PyObject
*namestr
= NULL
;
2150 static PyObject
*pathstr
= NULL
;
2151 static PyObject
*pkgstr
= NULL
;
2152 PyObject
*pkgname
, *modname
, *modpath
, *modules
, *parent
;
2154 if (globals
== NULL
|| !PyDict_Check(globals
) || !level
)
2157 if (namestr
== NULL
) {
2158 namestr
= PyString_InternFromString("__name__");
2159 if (namestr
== NULL
)
2162 if (pathstr
== NULL
) {
2163 pathstr
= PyString_InternFromString("__path__");
2164 if (pathstr
== NULL
)
2167 if (pkgstr
== NULL
) {
2168 pkgstr
= PyString_InternFromString("__package__");
2175 pkgname
= PyDict_GetItem(globals
, pkgstr
);
2177 if ((pkgname
!= NULL
) && (pkgname
!= Py_None
)) {
2178 /* __package__ is set, so use it */
2180 if (!PyString_Check(pkgname
)) {
2181 PyErr_SetString(PyExc_ValueError
,
2182 "__package__ set to non-string");
2185 len
= PyString_GET_SIZE(pkgname
);
2188 PyErr_SetString(PyExc_ValueError
,
2189 "Attempted relative import in non-package");
2194 if (len
> MAXPATHLEN
) {
2195 PyErr_SetString(PyExc_ValueError
,
2196 "Package name too long");
2199 strcpy(buf
, PyString_AS_STRING(pkgname
));
2201 /* __package__ not set, so figure it out and set it */
2202 modname
= PyDict_GetItem(globals
, namestr
);
2203 if (modname
== NULL
|| !PyString_Check(modname
))
2206 modpath
= PyDict_GetItem(globals
, pathstr
);
2207 if (modpath
!= NULL
) {
2208 /* __path__ is set, so modname is already the package name */
2209 Py_ssize_t len
= PyString_GET_SIZE(modname
);
2211 if (len
> MAXPATHLEN
) {
2212 PyErr_SetString(PyExc_ValueError
,
2213 "Module name too long");
2216 strcpy(buf
, PyString_AS_STRING(modname
));
2217 error
= PyDict_SetItem(globals
, pkgstr
, modname
);
2219 PyErr_SetString(PyExc_ValueError
,
2220 "Could not set __package__");
2224 /* Normal module, so work out the package name if any */
2225 char *start
= PyString_AS_STRING(modname
);
2226 char *lastdot
= strrchr(start
, '.');
2229 if (lastdot
== NULL
&& level
> 0) {
2230 PyErr_SetString(PyExc_ValueError
,
2231 "Attempted relative import in non-package");
2234 if (lastdot
== NULL
) {
2235 error
= PyDict_SetItem(globals
, pkgstr
, Py_None
);
2237 PyErr_SetString(PyExc_ValueError
,
2238 "Could not set __package__");
2243 len
= lastdot
- start
;
2244 if (len
>= MAXPATHLEN
) {
2245 PyErr_SetString(PyExc_ValueError
,
2246 "Module name too long");
2249 strncpy(buf
, start
, len
);
2251 pkgname
= PyString_FromString(buf
);
2252 if (pkgname
== NULL
) {
2255 error
= PyDict_SetItem(globals
, pkgstr
, pkgname
);
2258 PyErr_SetString(PyExc_ValueError
,
2259 "Could not set __package__");
2264 while (--level
> 0) {
2265 char *dot
= strrchr(buf
, '.');
2267 PyErr_SetString(PyExc_ValueError
,
2268 "Attempted relative import beyond "
2269 "toplevel package");
2274 *p_buflen
= strlen(buf
);
2276 modules
= PyImport_GetModuleDict();
2277 parent
= PyDict_GetItemString(modules
, buf
);
2279 PyErr_Format(PyExc_SystemError
,
2280 "Parent module '%.200s' not loaded", buf
);
2282 /* We expect, but can't guarantee, if parent != None, that:
2283 - parent.__name__ == buf
2284 - parent.__dict__ is globals
2285 If this is violated... Who cares? */
2288 /* altmod is either None or same as mod */
2290 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2291 Py_ssize_t
*p_buflen
)
2293 char *name
= *p_name
;
2294 char *dot
= strchr(name
, '.');
2299 if (strlen(name
) == 0) {
2300 /* completely empty module name should only happen in
2301 'from . import' (or '__import__("")')*/
2316 PyErr_SetString(PyExc_ValueError
,
2317 "Empty module name");
2321 p
= buf
+ *p_buflen
;
2324 if (p
+len
-buf
>= MAXPATHLEN
) {
2325 PyErr_SetString(PyExc_ValueError
,
2326 "Module name too long");
2329 strncpy(p
, name
, len
);
2331 *p_buflen
= p
+len
-buf
;
2333 result
= import_submodule(mod
, p
, buf
);
2334 if (result
== Py_None
&& altmod
!= mod
) {
2336 /* Here, altmod must be None and mod must not be None */
2337 result
= import_submodule(altmod
, p
, p
);
2338 if (result
!= NULL
&& result
!= Py_None
) {
2339 if (mark_miss(buf
) != 0) {
2343 strncpy(buf
, name
, len
);
2351 if (result
== Py_None
) {
2353 PyErr_Format(PyExc_ImportError
,
2354 "No module named %.200s", name
);
2362 mark_miss(char *name
)
2364 PyObject
*modules
= PyImport_GetModuleDict();
2365 return PyDict_SetItemString(modules
, name
, Py_None
);
2369 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, Py_ssize_t buflen
,
2374 if (!PyObject_HasAttrString(mod
, "__path__"))
2377 for (i
= 0; ; i
++) {
2378 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2381 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2387 if (!PyString_Check(item
)) {
2388 PyErr_SetString(PyExc_TypeError
,
2389 "Item in ``from list'' not a string");
2393 if (PyString_AS_STRING(item
)[0] == '*') {
2396 /* See if the package defines __all__ */
2398 continue; /* Avoid endless recursion */
2399 all
= PyObject_GetAttrString(mod
, "__all__");
2403 int ret
= ensure_fromlist(mod
, all
, buf
, buflen
, 1);
2410 hasit
= PyObject_HasAttr(mod
, item
);
2412 char *subname
= PyString_AS_STRING(item
);
2415 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2416 PyErr_SetString(PyExc_ValueError
,
2417 "Module name too long");
2424 submod
= import_submodule(mod
, subname
, buf
);
2426 if (submod
== NULL
) {
2438 add_submodule(PyObject
*mod
, PyObject
*submod
, char *fullname
, char *subname
,
2443 /* Irrespective of the success of this load, make a
2444 reference to it in the parent package module. A copy gets
2445 saved in the modules dictionary under the full name, so get a
2446 reference from there, if need be. (The exception is when the
2447 load failed with a SyntaxError -- then there's no trace in
2448 sys.modules. In that case, of course, do nothing extra.) */
2449 if (submod
== NULL
) {
2450 submod
= PyDict_GetItemString(modules
, fullname
);
2454 if (PyModule_Check(mod
)) {
2455 /* We can't use setattr here since it can give a
2456 * spurious warning if the submodule name shadows a
2458 PyObject
*dict
= PyModule_GetDict(mod
);
2461 if (PyDict_SetItemString(dict
, subname
, submod
) < 0)
2465 if (PyObject_SetAttrString(mod
, subname
, submod
) < 0)
2472 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2474 PyObject
*modules
= PyImport_GetModuleDict();
2478 if mod == None: subname == fullname
2479 else: mod.__name__ + "." + subname == fullname
2482 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2486 PyObject
*path
, *loader
= NULL
;
2487 char buf
[MAXPATHLEN
+1];
2488 struct filedescr
*fdp
;
2494 path
= PyObject_GetAttrString(mod
, "__path__");
2503 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2507 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2513 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2517 if (!add_submodule(mod
, m
, fullname
, subname
, modules
)) {
2527 /* Re-import a module of any kind and return its module object, WITH
2528 INCREMENTED REFERENCE COUNT */
2531 PyImport_ReloadModule(PyObject
*m
)
2533 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
2534 PyObject
*modules_reloading
= interp
->modules_reloading
;
2535 PyObject
*modules
= PyImport_GetModuleDict();
2536 PyObject
*path
= NULL
, *loader
= NULL
, *existing_m
= NULL
;
2537 char *name
, *subname
;
2538 char buf
[MAXPATHLEN
+1];
2539 struct filedescr
*fdp
;
2543 if (modules_reloading
== NULL
) {
2544 Py_FatalError("PyImport_ReloadModule: "
2545 "no modules_reloading dictionary!");
2549 if (m
== NULL
|| !PyModule_Check(m
)) {
2550 PyErr_SetString(PyExc_TypeError
,
2551 "reload() argument must be module");
2554 name
= PyModule_GetName(m
);
2557 if (m
!= PyDict_GetItemString(modules
, name
)) {
2558 PyErr_Format(PyExc_ImportError
,
2559 "reload(): module %.200s not in sys.modules",
2563 existing_m
= PyDict_GetItemString(modules_reloading
, name
);
2564 if (existing_m
!= NULL
) {
2565 /* Due to a recursive reload, this module is already
2567 Py_INCREF(existing_m
);
2570 if (PyDict_SetItemString(modules_reloading
, name
, m
) < 0)
2573 subname
= strrchr(name
, '.');
2574 if (subname
== NULL
)
2577 PyObject
*parentname
, *parent
;
2578 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2579 if (parentname
== NULL
) {
2580 imp_modules_reloading_clear();
2583 parent
= PyDict_GetItem(modules
, parentname
);
2584 if (parent
== NULL
) {
2585 PyErr_Format(PyExc_ImportError
,
2586 "reload(): parent %.200s not in sys.modules",
2587 PyString_AS_STRING(parentname
));
2588 Py_DECREF(parentname
);
2589 imp_modules_reloading_clear();
2592 Py_DECREF(parentname
);
2594 path
= PyObject_GetAttrString(parent
, "__path__");
2599 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, &loader
);
2604 imp_modules_reloading_clear();
2608 newm
= load_module(name
, fp
, buf
, fdp
->type
, loader
);
2614 /* load_module probably removed name from modules because of
2615 * the error. Put back the original module object. We're
2616 * going to return NULL in this case regardless of whether
2617 * replacing name succeeds, so the return value is ignored.
2619 PyDict_SetItemString(modules
, name
, m
);
2621 imp_modules_reloading_clear();
2626 /* Higher-level import emulator which emulates the "import" statement
2627 more accurately -- it invokes the __import__() function from the
2628 builtins of the current globals. This means that the import is
2629 done using whatever import hooks are installed in the current
2630 environment, e.g. by "rexec".
2631 A dummy list ["__doc__"] is passed as the 4th argument so that
2632 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2633 will return <module "gencache"> instead of <module "win32com">. */
2636 PyImport_Import(PyObject
*module_name
)
2638 static PyObject
*silly_list
= NULL
;
2639 static PyObject
*builtins_str
= NULL
;
2640 static PyObject
*import_str
= NULL
;
2641 PyObject
*globals
= NULL
;
2642 PyObject
*import
= NULL
;
2643 PyObject
*builtins
= NULL
;
2646 /* Initialize constant string objects */
2647 if (silly_list
== NULL
) {
2648 import_str
= PyString_InternFromString("__import__");
2649 if (import_str
== NULL
)
2651 builtins_str
= PyString_InternFromString("__builtins__");
2652 if (builtins_str
== NULL
)
2654 silly_list
= Py_BuildValue("[s]", "__doc__");
2655 if (silly_list
== NULL
)
2659 /* Get the builtins from current globals */
2660 globals
= PyEval_GetGlobals();
2661 if (globals
!= NULL
) {
2663 builtins
= PyObject_GetItem(globals
, builtins_str
);
2664 if (builtins
== NULL
)
2668 /* No globals -- use standard builtins, and fake globals */
2671 builtins
= PyImport_ImportModuleLevel("__builtin__",
2672 NULL
, NULL
, NULL
, 0);
2673 if (builtins
== NULL
)
2675 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2676 if (globals
== NULL
)
2680 /* Get the __import__ function from the builtins */
2681 if (PyDict_Check(builtins
)) {
2682 import
= PyObject_GetItem(builtins
, import_str
);
2684 PyErr_SetObject(PyExc_KeyError
, import_str
);
2687 import
= PyObject_GetAttr(builtins
, import_str
);
2691 /* Call the __import__ function with the proper argument list
2692 * Always use absolute import here. */
2693 r
= PyObject_CallFunction(import
, "OOOOi", module_name
, globals
,
2694 globals
, silly_list
, 0, NULL
);
2697 Py_XDECREF(globals
);
2698 Py_XDECREF(builtins
);
2705 /* Module 'imp' provides Python access to the primitives used for
2710 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2714 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2715 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2716 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2717 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2719 return PyString_FromStringAndSize(buf
, 4);
2723 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2726 struct filedescr
*fdp
;
2728 list
= PyList_New(0);
2731 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2732 PyObject
*item
= Py_BuildValue("ssi",
2733 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2738 if (PyList_Append(list
, item
) < 0) {
2749 call_find_module(char *name
, PyObject
*path
)
2751 extern int fclose(FILE *);
2752 PyObject
*fob
, *ret
;
2753 struct filedescr
*fdp
;
2754 char pathname
[MAXPATHLEN
+1];
2758 if (path
== Py_None
)
2760 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2764 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2774 ret
= Py_BuildValue("Os(ssi)",
2775 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2781 imp_find_module(PyObject
*self
, PyObject
*args
)
2784 PyObject
*path
= NULL
;
2785 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2787 return call_find_module(name
, path
);
2791 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2796 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2798 ret
= init_builtin(name
);
2805 m
= PyImport_AddModule(name
);
2811 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2816 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2818 ret
= PyImport_ImportFrozenModule(name
);
2825 m
= PyImport_AddModule(name
);
2831 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2835 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2837 return get_frozen_object(name
);
2841 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2844 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2846 return PyInt_FromLong(is_builtin(name
));
2850 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2854 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2856 p
= find_frozen(name
);
2857 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2861 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2866 mode
= "r" PY_STDIOTEXTMODE
;
2867 fp
= fopen(pathname
, mode
);
2869 PyErr_SetFromErrno(PyExc_IOError
);
2872 fp
= PyFile_AsFile(fob
);
2874 PyErr_SetString(PyExc_ValueError
,
2875 "bad/closed file object");
2881 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2885 PyObject
*fob
= NULL
;
2888 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2889 &PyFile_Type
, &fob
))
2891 fp
= get_file(pathname
, fob
, "rb");
2894 m
= load_compiled_module(name
, pathname
, fp
);
2900 #ifdef HAVE_DYNAMIC_LOADING
2903 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2907 PyObject
*fob
= NULL
;
2910 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2911 &PyFile_Type
, &fob
))
2914 fp
= get_file(pathname
, fob
, "r");
2918 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2922 #endif /* HAVE_DYNAMIC_LOADING */
2925 imp_load_source(PyObject
*self
, PyObject
*args
)
2929 PyObject
*fob
= NULL
;
2932 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2933 &PyFile_Type
, &fob
))
2935 fp
= get_file(pathname
, fob
, "r");
2938 m
= load_source_module(name
, pathname
, fp
);
2945 imp_load_module(PyObject
*self
, PyObject
*args
)
2950 char *suffix
; /* Unused */
2955 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2956 &name
, &fob
, &pathname
,
2957 &suffix
, &mode
, &type
))
2960 /* Mode must start with 'r' or 'U' and must not contain '+'.
2961 Implicit in this test is the assumption that the mode
2962 may contain other modifiers like 'b' or 't'. */
2964 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2965 PyErr_Format(PyExc_ValueError
,
2966 "invalid file open mode %.200s", mode
);
2973 if (!PyFile_Check(fob
)) {
2974 PyErr_SetString(PyExc_ValueError
,
2975 "load_module arg#2 should be a file or None");
2978 fp
= get_file(pathname
, fob
, mode
);
2982 return load_module(name
, fp
, pathname
, type
, NULL
);
2986 imp_load_package(PyObject
*self
, PyObject
*args
)
2990 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2992 return load_package(name
, pathname
);
2996 imp_new_module(PyObject
*self
, PyObject
*args
)
2999 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
3001 return PyModule_New(name
);
3006 PyDoc_STRVAR(doc_imp
,
3007 "This module provides the components needed to build your own\n\
3008 __import__ function. Undocumented functions are obsolete.");
3010 PyDoc_STRVAR(doc_find_module
,
3011 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
3012 Search for a module. If path is omitted or None, search for a\n\
3013 built-in, frozen or special module and continue search in sys.path.\n\
3014 The module name cannot contain '.'; to search for a submodule of a\n\
3015 package, pass the submodule name and the package's __path__.");
3017 PyDoc_STRVAR(doc_load_module
,
3018 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
3019 Load a module, given information returned by find_module().\n\
3020 The module name must include the full package name, if any.");
3022 PyDoc_STRVAR(doc_get_magic
,
3023 "get_magic() -> string\n\
3024 Return the magic number for .pyc or .pyo files.");
3026 PyDoc_STRVAR(doc_get_suffixes
,
3027 "get_suffixes() -> [(suffix, mode, type), ...]\n\
3028 Return a list of (suffix, mode, type) tuples describing the files\n\
3029 that find_module() looks for.");
3031 PyDoc_STRVAR(doc_new_module
,
3032 "new_module(name) -> module\n\
3033 Create a new module. Do not enter it in sys.modules.\n\
3034 The module name must include the full package name, if any.");
3036 PyDoc_STRVAR(doc_lock_held
,
3037 "lock_held() -> boolean\n\
3038 Return True if the import lock is currently held, else False.\n\
3039 On platforms without threads, return False.");
3041 PyDoc_STRVAR(doc_acquire_lock
,
3042 "acquire_lock() -> None\n\
3043 Acquires the interpreter's import lock for the current thread.\n\
3044 This lock should be used by import hooks to ensure thread-safety\n\
3045 when importing modules.\n\
3046 On platforms without threads, this function does nothing.");
3048 PyDoc_STRVAR(doc_release_lock
,
3049 "release_lock() -> None\n\
3050 Release the interpreter's import lock.\n\
3051 On platforms without threads, this function does nothing.");
3053 static PyMethodDef imp_methods
[] = {
3054 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
3055 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
3056 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
3057 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
3058 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
3059 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
3060 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
3061 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
3062 /* The rest are obsolete */
3063 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
3064 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
3065 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
3066 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
3067 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
3068 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
3069 #ifdef HAVE_DYNAMIC_LOADING
3070 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
3072 {"load_package", imp_load_package
, METH_VARARGS
},
3073 {"load_source", imp_load_source
, METH_VARARGS
},
3074 {NULL
, NULL
} /* sentinel */
3078 setint(PyObject
*d
, char *name
, int value
)
3083 v
= PyInt_FromLong((long)value
);
3084 err
= PyDict_SetItemString(d
, name
, v
);
3094 NullImporter_init(NullImporter
*self
, PyObject
*args
, PyObject
*kwds
)
3099 if (!_PyArg_NoKeywords("NullImporter()", kwds
))
3102 if (!PyArg_ParseTuple(args
, "s:NullImporter",
3106 pathlen
= strlen(path
);
3108 PyErr_SetString(PyExc_ImportError
, "empty pathname");
3112 struct stat statbuf
;
3115 rv
= stat(path
, &statbuf
);
3117 /* MS Windows stat() chokes on paths like C:\path\. Try to
3118 * recover *one* time by stripping off a trailing slash or
3119 * backslash. http://bugs.python.org/issue1293
3121 if (rv
!= 0 && pathlen
<= MAXPATHLEN
&&
3122 (path
[pathlen
-1] == '/' || path
[pathlen
-1] == '\\')) {
3123 char mangled
[MAXPATHLEN
+1];
3125 strcpy(mangled
, path
);
3126 mangled
[pathlen
-1] = '\0';
3127 rv
= stat(mangled
, &statbuf
);
3132 if (S_ISDIR(statbuf
.st_mode
)) {
3133 /* it's a directory */
3134 PyErr_SetString(PyExc_ImportError
,
3135 "existing directory");
3140 if (object_exists(path
)) {
3143 /* it's a directory */
3144 PyErr_SetString(PyExc_ImportError
,
3145 "existing directory");
3155 NullImporter_find_module(NullImporter
*self
, PyObject
*args
)
3160 static PyMethodDef NullImporter_methods
[] = {
3161 {"find_module", (PyCFunction
)NullImporter_find_module
, METH_VARARGS
,
3162 "Always return None"
3164 {NULL
} /* Sentinel */
3168 PyTypeObject PyNullImporter_Type
= {
3169 PyVarObject_HEAD_INIT(NULL
, 0)
3170 "imp.NullImporter", /*tp_name*/
3171 sizeof(NullImporter
), /*tp_basicsize*/
3180 0, /*tp_as_sequence*/
3181 0, /*tp_as_mapping*/
3188 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
3189 "Null importer object", /* tp_doc */
3190 0, /* tp_traverse */
3192 0, /* tp_richcompare */
3193 0, /* tp_weaklistoffset */
3195 0, /* tp_iternext */
3196 NullImporter_methods
, /* tp_methods */
3201 0, /* tp_descr_get */
3202 0, /* tp_descr_set */
3203 0, /* tp_dictoffset */
3204 (initproc
)NullImporter_init
, /* tp_init */
3206 PyType_GenericNew
/* tp_new */
3215 if (PyType_Ready(&PyNullImporter_Type
) < 0)
3218 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
3219 NULL
, PYTHON_API_VERSION
);
3222 d
= PyModule_GetDict(m
);
3226 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
3227 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
3228 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
3229 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
3230 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
3231 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
3232 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
3233 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
3234 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
3235 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
3237 Py_INCREF(&PyNullImporter_Type
);
3238 PyModule_AddObject(m
, "NullImporter", (PyObject
*)&PyNullImporter_Type
);
3244 /* API for embedding applications that want to add their own entries
3245 to the table of built-in modules. This should normally be called
3246 *before* Py_Initialize(). When the table resize fails, -1 is
3247 returned and the existing table is unchanged.
3249 After a similar function by Just van Rossum. */
3252 PyImport_ExtendInittab(struct _inittab
*newtab
)
3254 static struct _inittab
*our_copy
= NULL
;
3258 /* Count the number of entries in both tables */
3259 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
3262 return 0; /* Nothing to do */
3263 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
3266 /* Allocate new memory for the combined table */
3268 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
3272 /* Copy the tables into the new memory */
3273 if (our_copy
!= PyImport_Inittab
)
3274 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
3275 PyImport_Inittab
= our_copy
= p
;
3276 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
3281 /* Shorthand to add a single entry given a name and a function */
3284 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
3286 struct _inittab newtab
[2];
3288 memset(newtab
, '\0', sizeof newtab
);
3290 newtab
[0].name
= name
;
3291 newtab
[0].initfunc
= initfunc
;
3293 return PyImport_ExtendInittab(newtab
);