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: 62141 (peephole optimizations)
72 #define MAGIC (62141 | ((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
},
107 static PyTypeObject NullImporterType
; /* Forward reference */
109 /* Initialize things */
114 const struct filedescr
*scan
;
115 struct filedescr
*filetab
;
119 /* prepare _PyImport_Filetab: copy entries from
120 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
122 #ifdef HAVE_DYNAMIC_LOADING
123 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
126 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
128 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
130 Py_FatalError("Can't initialize import file table.");
131 #ifdef HAVE_DYNAMIC_LOADING
132 memcpy(filetab
, _PyImport_DynLoadFiletab
,
133 countD
* sizeof(struct filedescr
));
135 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
136 countS
* sizeof(struct filedescr
));
137 filetab
[countD
+ countS
].suffix
= NULL
;
139 _PyImport_Filetab
= filetab
;
141 if (Py_OptimizeFlag
) {
142 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
143 for (; filetab
->suffix
!= NULL
; filetab
++) {
145 if (strcmp(filetab
->suffix
, ".pyc") == 0)
146 filetab
->suffix
= ".pyo";
148 if (strcmp(filetab
->suffix
, "/pyc") == 0)
149 filetab
->suffix
= "/pyo";
154 if (Py_UnicodeFlag
) {
155 /* Fix the pyc_magic so that byte compiled code created
156 using the all-Unicode method doesn't interfere with
157 code created in normal operation mode. */
158 pyc_magic
= MAGIC
+ 1;
163 _PyImportHooks_Init(void)
165 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
168 /* adding sys.path_hooks and sys.path_importer_cache, setting up
170 if (PyType_Ready(&NullImporterType
) < 0)
174 PySys_WriteStderr("# installing zipimport hook\n");
179 err
= PySys_SetObject("meta_path", v
);
186 err
= PySys_SetObject("path_importer_cache", v
);
190 path_hooks
= PyList_New(0);
191 if (path_hooks
== NULL
)
193 err
= PySys_SetObject("path_hooks", path_hooks
);
197 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
198 "path_importer_cache, or NullImporter failed"
202 zimpimport
= PyImport_ImportModule("zipimport");
203 if (zimpimport
== NULL
) {
204 PyErr_Clear(); /* No zip import module -- okay */
206 PySys_WriteStderr("# can't import zipimport\n");
209 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
211 Py_DECREF(zimpimport
);
212 if (zipimporter
== NULL
) {
213 PyErr_Clear(); /* No zipimporter object -- okay */
216 "# can't import zipimport.zipimporter\n");
219 /* sys.path_hooks.append(zipimporter) */
220 err
= PyList_Append(path_hooks
, zipimporter
);
221 Py_DECREF(zipimporter
);
226 "# installed zipimport hook\n");
229 Py_DECREF(path_hooks
);
235 Py_XDECREF(extensions
);
237 PyMem_DEL(_PyImport_Filetab
);
238 _PyImport_Filetab
= NULL
;
242 /* Locking primitives to prevent parallel imports of the same module
243 in different threads to return with a partially loaded module.
244 These calls are serialized by the global interpreter lock. */
248 #include "pythread.h"
250 static PyThread_type_lock import_lock
= 0;
251 static long import_lock_thread
= -1;
252 static int import_lock_level
= 0;
257 long me
= PyThread_get_thread_ident();
259 return; /* Too bad */
260 if (import_lock
== NULL
) {
261 import_lock
= PyThread_allocate_lock();
262 if (import_lock
== NULL
)
263 return; /* Nothing much we can do. */
265 if (import_lock_thread
== me
) {
269 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
271 PyThreadState
*tstate
= PyEval_SaveThread();
272 PyThread_acquire_lock(import_lock
, 1);
273 PyEval_RestoreThread(tstate
);
275 import_lock_thread
= me
;
276 import_lock_level
= 1;
282 long me
= PyThread_get_thread_ident();
283 if (me
== -1 || import_lock
== NULL
)
284 return 0; /* Too bad */
285 if (import_lock_thread
!= me
)
288 if (import_lock_level
== 0) {
289 import_lock_thread
= -1;
290 PyThread_release_lock(import_lock
);
295 /* This function is called from PyOS_AfterFork to ensure that newly
296 created child processes do not share locks with the parent. */
299 _PyImport_ReInitLock(void)
302 if (import_lock
!= NULL
)
303 import_lock
= PyThread_allocate_lock();
309 #define lock_import()
310 #define unlock_import() 0
315 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
318 return PyBool_FromLong(import_lock_thread
!= -1);
320 return PyBool_FromLong(0);
325 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
335 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
338 if (unlock_import() < 0) {
339 PyErr_SetString(PyExc_RuntimeError
,
340 "not holding the import lock");
349 imp_modules_reloading_clear(void)
351 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
352 if (interp
->modules_reloading
!= NULL
)
353 PyDict_Clear(interp
->modules_reloading
);
359 PyImport_GetModuleDict(void)
361 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
362 if (interp
->modules
== NULL
)
363 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
364 return interp
->modules
;
368 /* List of names to clear in sys */
369 static char* sys_deletes
[] = {
370 "path", "argv", "ps1", "ps2", "exitfunc",
371 "exc_type", "exc_value", "exc_traceback",
372 "last_type", "last_value", "last_traceback",
373 "path_hooks", "path_importer_cache", "meta_path",
377 static char* sys_files
[] = {
378 "stdin", "__stdin__",
379 "stdout", "__stdout__",
380 "stderr", "__stderr__",
385 /* Un-initialize things, as good as we can */
388 PyImport_Cleanup(void)
390 Py_ssize_t pos
, ndone
;
392 PyObject
*key
, *value
, *dict
;
393 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
394 PyObject
*modules
= interp
->modules
;
397 return; /* Already done */
399 /* Delete some special variables first. These are common
400 places where user values hide and people complain when their
401 destructors fail. Since the modules containing them are
402 deleted *last* of all, they would come too late in the normal
403 destruction order. Sigh. */
405 value
= PyDict_GetItemString(modules
, "__builtin__");
406 if (value
!= NULL
&& PyModule_Check(value
)) {
407 dict
= PyModule_GetDict(value
);
409 PySys_WriteStderr("# clear __builtin__._\n");
410 PyDict_SetItemString(dict
, "_", Py_None
);
412 value
= PyDict_GetItemString(modules
, "sys");
413 if (value
!= NULL
&& PyModule_Check(value
)) {
416 dict
= PyModule_GetDict(value
);
417 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
419 PySys_WriteStderr("# clear sys.%s\n", *p
);
420 PyDict_SetItemString(dict
, *p
, Py_None
);
422 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
424 PySys_WriteStderr("# restore sys.%s\n", *p
);
425 v
= PyDict_GetItemString(dict
, *(p
+1));
428 PyDict_SetItemString(dict
, *p
, v
);
432 /* First, delete __main__ */
433 value
= PyDict_GetItemString(modules
, "__main__");
434 if (value
!= NULL
&& PyModule_Check(value
)) {
436 PySys_WriteStderr("# cleanup __main__\n");
437 _PyModule_Clear(value
);
438 PyDict_SetItemString(modules
, "__main__", Py_None
);
441 /* The special treatment of __builtin__ here is because even
442 when it's not referenced as a module, its dictionary is
443 referenced by almost every module's __builtins__. Since
444 deleting a module clears its dictionary (even if there are
445 references left to it), we need to delete the __builtin__
446 module last. Likewise, we don't delete sys until the very
447 end because it is implicitly referenced (e.g. by print).
449 Also note that we 'delete' modules by replacing their entry
450 in the modules dict with None, rather than really deleting
451 them; this avoids a rehash of the modules dictionary and
452 also marks them as "non existent" so they won't be
455 /* Next, repeatedly delete modules with a reference count of
456 one (skipping __builtin__ and sys) and delete them */
460 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
461 if (value
->ob_refcnt
!= 1)
463 if (PyString_Check(key
) && PyModule_Check(value
)) {
464 name
= PyString_AS_STRING(key
);
465 if (strcmp(name
, "__builtin__") == 0)
467 if (strcmp(name
, "sys") == 0)
471 "# cleanup[1] %s\n", name
);
472 _PyModule_Clear(value
);
473 PyDict_SetItem(modules
, key
, Py_None
);
479 /* Next, delete all modules (still skipping __builtin__ and sys) */
481 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
482 if (PyString_Check(key
) && PyModule_Check(value
)) {
483 name
= PyString_AS_STRING(key
);
484 if (strcmp(name
, "__builtin__") == 0)
486 if (strcmp(name
, "sys") == 0)
489 PySys_WriteStderr("# cleanup[2] %s\n", name
);
490 _PyModule_Clear(value
);
491 PyDict_SetItem(modules
, key
, Py_None
);
495 /* Next, delete sys and __builtin__ (in that order) */
496 value
= PyDict_GetItemString(modules
, "sys");
497 if (value
!= NULL
&& PyModule_Check(value
)) {
499 PySys_WriteStderr("# cleanup sys\n");
500 _PyModule_Clear(value
);
501 PyDict_SetItemString(modules
, "sys", Py_None
);
503 value
= PyDict_GetItemString(modules
, "__builtin__");
504 if (value
!= NULL
&& PyModule_Check(value
)) {
506 PySys_WriteStderr("# cleanup __builtin__\n");
507 _PyModule_Clear(value
);
508 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
511 /* Finally, clear and delete the modules directory */
512 PyDict_Clear(modules
);
513 interp
->modules
= NULL
;
515 Py_CLEAR(interp
->modules_reloading
);
519 /* Helper for pythonrun.c -- return magic number */
522 PyImport_GetMagicNumber(void)
528 /* Magic for extension modules (built-in as well as dynamically
529 loaded). To prevent initializing an extension module more than
530 once, we keep a static dictionary 'extensions' keyed by module name
531 (for built-in modules) or by filename (for dynamically loaded
532 modules), containing these modules. A copy of the module's
533 dictionary is stored by calling _PyImport_FixupExtension()
534 immediately after the module initialization function succeeds. A
535 copy can be retrieved from there by calling
536 _PyImport_FindExtension(). */
539 _PyImport_FixupExtension(char *name
, char *filename
)
541 PyObject
*modules
, *mod
, *dict
, *copy
;
542 if (extensions
== NULL
) {
543 extensions
= PyDict_New();
544 if (extensions
== NULL
)
547 modules
= PyImport_GetModuleDict();
548 mod
= PyDict_GetItemString(modules
, name
);
549 if (mod
== NULL
|| !PyModule_Check(mod
)) {
550 PyErr_Format(PyExc_SystemError
,
551 "_PyImport_FixupExtension: module %.200s not loaded", name
);
554 dict
= PyModule_GetDict(mod
);
557 copy
= PyDict_Copy(dict
);
560 PyDict_SetItemString(extensions
, filename
, copy
);
566 _PyImport_FindExtension(char *name
, char *filename
)
568 PyObject
*dict
, *mod
, *mdict
;
569 if (extensions
== NULL
)
571 dict
= PyDict_GetItemString(extensions
, filename
);
574 mod
= PyImport_AddModule(name
);
577 mdict
= PyModule_GetDict(mod
);
580 if (PyDict_Update(mdict
, dict
))
583 PySys_WriteStderr("import %s # previously loaded (%s)\n",
589 /* Get the module object corresponding to a module name.
590 First check the modules dictionary if there's one there,
591 if not, create a new one and insert it in the modules dictionary.
592 Because the former action is most common, THIS DOES NOT RETURN A
596 PyImport_AddModule(const char *name
)
598 PyObject
*modules
= PyImport_GetModuleDict();
601 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
604 m
= PyModule_New(name
);
607 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
611 Py_DECREF(m
); /* Yes, it still exists, in modules! */
616 /* Remove name from sys.modules, if it's there. */
618 _RemoveModule(const char *name
)
620 PyObject
*modules
= PyImport_GetModuleDict();
621 if (PyDict_GetItemString(modules
, name
) == NULL
)
623 if (PyDict_DelItemString(modules
, name
) < 0)
624 Py_FatalError("import: deleting existing key in"
625 "sys.modules failed");
628 /* Execute a code object in a module and return the module object
629 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
630 * removed from sys.modules, to avoid leaving damaged module objects
631 * in sys.modules. The caller may wish to restore the original
632 * module object (if any) in this case; PyImport_ReloadModule is an
636 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
638 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
642 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
644 PyObject
*modules
= PyImport_GetModuleDict();
647 m
= PyImport_AddModule(name
);
650 /* If the module is being reloaded, we get the old module back
651 and re-use its dict to exec the new code. */
652 d
= PyModule_GetDict(m
);
653 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
654 if (PyDict_SetItemString(d
, "__builtins__",
655 PyEval_GetBuiltins()) != 0)
658 /* Remember the filename as the __file__ attribute */
660 if (pathname
!= NULL
) {
661 v
= PyString_FromString(pathname
);
666 v
= ((PyCodeObject
*)co
)->co_filename
;
669 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
670 PyErr_Clear(); /* Not important enough to report */
673 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
678 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
679 PyErr_Format(PyExc_ImportError
,
680 "Loaded module %.200s not found in sys.modules",
695 /* Given a pathname for a Python source file, fill a buffer with the
696 pathname for the corresponding compiled file. Return the pathname
697 for the compiled file, or NULL if there's no space in the buffer.
698 Doesn't set an exception. */
701 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
703 size_t len
= strlen(pathname
);
708 /* Treat .pyw as if it were .py. The case of ".pyw" must match
709 that used in _PyImport_StandardFiletab. */
710 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
711 --len
; /* pretend 'w' isn't there */
713 memcpy(buf
, pathname
, len
);
714 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
721 /* Given a pathname for a Python source file, its time of last
722 modification, and a pathname for a compiled file, check whether the
723 compiled file represents the same version of the source. If so,
724 return a FILE pointer for the compiled file, positioned just after
725 the header; if not, return NULL.
726 Doesn't set an exception. */
729 check_compiled_module(char *pathname
, time_t mtime
, char *cpathname
)
735 fp
= fopen(cpathname
, "rb");
738 magic
= PyMarshal_ReadLongFromFile(fp
);
739 if (magic
!= pyc_magic
) {
741 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
745 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
746 if (pyc_mtime
!= mtime
) {
748 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
753 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
758 /* Read a code object from a file and check it for validity */
760 static PyCodeObject
*
761 read_compiled_module(char *cpathname
, FILE *fp
)
765 co
= PyMarshal_ReadLastObjectFromFile(fp
);
768 if (!PyCode_Check(co
)) {
769 PyErr_Format(PyExc_ImportError
,
770 "Non-code object in %.200s", cpathname
);
774 return (PyCodeObject
*)co
;
778 /* Load a module from a compiled file, execute it, and return its
779 module object WITH INCREMENTED REFERENCE COUNT */
782 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
788 magic
= PyMarshal_ReadLongFromFile(fp
);
789 if (magic
!= pyc_magic
) {
790 PyErr_Format(PyExc_ImportError
,
791 "Bad magic number in %.200s", cpathname
);
794 (void) PyMarshal_ReadLongFromFile(fp
);
795 co
= read_compiled_module(cpathname
, fp
);
799 PySys_WriteStderr("import %s # precompiled from %s\n",
801 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
807 /* Parse a source file and return the corresponding code object */
809 static PyCodeObject
*
810 parse_source_module(const char *pathname
, FILE *fp
)
812 PyCodeObject
*co
= NULL
;
814 PyArena
*arena
= PyArena_New();
818 mod
= PyParser_ASTFromFile(fp
, pathname
, Py_file_input
, 0, 0, 0,
821 co
= PyAST_Compile(mod
, pathname
, NULL
, arena
);
828 /* Helper to open a bytecode file for writing in exclusive mode */
831 open_exclusive(char *filename
)
833 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
834 /* Use O_EXCL to avoid a race condition when another process tries to
835 write the same file. When that happens, our open() call fails,
836 which is just fine (since it's only a cache).
837 XXX If the file exists and is writable but the directory is not
838 writable, the file will never be written. Oh well.
841 (void) unlink(filename
);
842 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
844 |O_BINARY
/* necessary for Windows */
847 , 0666, "ctxt=bin", "shr=nil"
854 return fdopen(fd
, "wb");
856 /* Best we can do -- on Windows this can't happen anyway */
857 return fopen(filename
, "wb");
862 /* Write a compiled module to a file, placing the time of last
863 modification of its source into the header.
864 Errors are ignored, if a write error occurs an attempt is made to
868 write_compiled_module(PyCodeObject
*co
, char *cpathname
, time_t mtime
)
872 fp
= open_exclusive(cpathname
);
876 "# can't create %s\n", cpathname
);
879 PyMarshal_WriteLongToFile(pyc_magic
, fp
, Py_MARSHAL_VERSION
);
880 /* First write a 0 for mtime */
881 PyMarshal_WriteLongToFile(0L, fp
, Py_MARSHAL_VERSION
);
882 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
, Py_MARSHAL_VERSION
);
883 if (fflush(fp
) != 0 || ferror(fp
)) {
885 PySys_WriteStderr("# can't write %s\n", cpathname
);
886 /* Don't keep partial file */
888 (void) unlink(cpathname
);
891 /* Now write the true mtime */
893 assert(mtime
< LONG_MAX
);
894 PyMarshal_WriteLongToFile((long)mtime
, fp
, Py_MARSHAL_VERSION
);
898 PySys_WriteStderr("# wrote %s\n", cpathname
);
902 /* Load a source module from a given file and return its module
903 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
904 byte-compiled file, use that instead. */
907 load_source_module(char *name
, char *pathname
, FILE *fp
)
911 char buf
[MAXPATHLEN
+1];
916 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
917 if (mtime
== (time_t)(-1)) {
918 PyErr_Format(PyExc_RuntimeError
,
919 "unable to get modification time from '%s'",
923 #if SIZEOF_TIME_T > 4
924 /* Python's .pyc timestamp handling presumes that the timestamp fits
925 in 4 bytes. This will be fine until sometime in the year 2038,
926 when a 4-byte signed time_t will overflow.
929 PyErr_SetString(PyExc_OverflowError
,
930 "modification time overflows a 4 byte field");
934 cpathname
= make_compiled_pathname(pathname
, buf
,
935 (size_t)MAXPATHLEN
+ 1);
936 if (cpathname
!= NULL
&&
937 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
938 co
= read_compiled_module(cpathname
, fpc
);
943 PySys_WriteStderr("import %s # precompiled from %s\n",
945 pathname
= cpathname
;
948 co
= parse_source_module(pathname
, fp
);
952 PySys_WriteStderr("import %s # from %s\n",
955 write_compiled_module(co
, cpathname
, mtime
);
957 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
965 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
966 static struct filedescr
*find_module(char *, char *, PyObject
*,
967 char *, size_t, FILE **, PyObject
**);
968 static struct _frozen
*find_frozen(char *name
);
970 /* Load a package and return its module object WITH INCREMENTED
974 load_package(char *name
, char *pathname
)
977 PyObject
*file
= NULL
;
978 PyObject
*path
= NULL
;
980 char buf
[MAXPATHLEN
+1];
982 struct filedescr
*fdp
;
984 m
= PyImport_AddModule(name
);
988 PySys_WriteStderr("import %s # directory %s\n",
990 d
= PyModule_GetDict(m
);
991 file
= PyString_FromString(pathname
);
994 path
= Py_BuildValue("[O]", file
);
997 err
= PyDict_SetItemString(d
, "__file__", file
);
999 err
= PyDict_SetItemString(d
, "__path__", path
);
1003 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
1005 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1013 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
1027 /* Helper to test for built-in module */
1030 is_builtin(char *name
)
1033 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
1034 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
1035 if (PyImport_Inittab
[i
].initfunc
== NULL
)
1045 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1046 possibly by fetching it from the path_importer_cache dict. If it
1047 wasn't yet cached, traverse path_hooks until a hook is found
1048 that can handle the path item. Return None if no hook could;
1049 this tells our caller it should fall back to the builtin
1050 import mechanism. Cache the result in path_importer_cache.
1051 Returns a borrowed reference. */
1054 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
1058 Py_ssize_t j
, nhooks
;
1060 /* These conditions are the caller's responsibility: */
1061 assert(PyList_Check(path_hooks
));
1062 assert(PyDict_Check(path_importer_cache
));
1064 nhooks
= PyList_Size(path_hooks
);
1066 return NULL
; /* Shouldn't happen */
1068 importer
= PyDict_GetItem(path_importer_cache
, p
);
1069 if (importer
!= NULL
)
1072 /* set path_importer_cache[p] to None to avoid recursion */
1073 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1076 for (j
= 0; j
< nhooks
; j
++) {
1077 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1080 importer
= PyObject_CallFunctionObjArgs(hook
, p
, NULL
);
1081 if (importer
!= NULL
)
1084 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1089 if (importer
== NULL
) {
1090 importer
= PyObject_CallFunctionObjArgs(
1091 (PyObject
*)&NullImporterType
, p
, NULL
1093 if (importer
== NULL
) {
1094 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1100 if (importer
!= NULL
) {
1101 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1102 Py_DECREF(importer
);
1109 /* Search the path (default sys.path) for a module. Return the
1110 corresponding filedescr struct, and (via return arguments) the
1111 pathname and an open file. Return NULL if the module is not found. */
1114 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1115 char *, Py_ssize_t
);
1118 static int case_ok(char *, Py_ssize_t
, Py_ssize_t
, char *);
1119 static int find_init_module(char *); /* Forward */
1120 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1122 static struct filedescr
*
1123 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1124 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1126 Py_ssize_t i
, npath
;
1127 size_t len
, namelen
;
1128 struct filedescr
*fdp
= NULL
;
1131 PyObject
*path_hooks
, *path_importer_cache
;
1133 struct stat statbuf
;
1135 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1136 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1137 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1138 char name
[MAXPATHLEN
+1];
1139 #if defined(PYOS_OS2)
1141 size_t saved_namelen
;
1142 char *saved_buf
= NULL
;
1144 if (p_loader
!= NULL
)
1147 if (strlen(subname
) > MAXPATHLEN
) {
1148 PyErr_SetString(PyExc_OverflowError
,
1149 "module name is too long");
1152 strcpy(name
, subname
);
1154 /* sys.meta_path import hook */
1155 if (p_loader
!= NULL
) {
1156 PyObject
*meta_path
;
1158 meta_path
= PySys_GetObject("meta_path");
1159 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1160 PyErr_SetString(PyExc_ImportError
,
1161 "sys.meta_path must be a list of "
1165 Py_INCREF(meta_path
); /* zap guard */
1166 npath
= PyList_Size(meta_path
);
1167 for (i
= 0; i
< npath
; i
++) {
1169 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1170 loader
= PyObject_CallMethod(hook
, "find_module",
1174 if (loader
== NULL
) {
1175 Py_DECREF(meta_path
);
1176 return NULL
; /* true error */
1178 if (loader
!= Py_None
) {
1179 /* a loader was found */
1181 Py_DECREF(meta_path
);
1182 return &importhookdescr
;
1186 Py_DECREF(meta_path
);
1189 if (path
!= NULL
&& PyString_Check(path
)) {
1190 /* The only type of submodule allowed inside a "frozen"
1191 package are other frozen modules or packages. */
1192 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1193 PyErr_SetString(PyExc_ImportError
,
1194 "full frozen module name too long");
1197 strcpy(buf
, PyString_AsString(path
));
1201 if (find_frozen(name
) != NULL
) {
1205 PyErr_Format(PyExc_ImportError
,
1206 "No frozen submodule named %.200s", name
);
1210 if (is_builtin(name
)) {
1214 if ((find_frozen(name
)) != NULL
) {
1220 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1226 path
= PySys_GetObject("path");
1228 if (path
== NULL
|| !PyList_Check(path
)) {
1229 PyErr_SetString(PyExc_ImportError
,
1230 "sys.path must be a list of directory names");
1234 path_hooks
= PySys_GetObject("path_hooks");
1235 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1236 PyErr_SetString(PyExc_ImportError
,
1237 "sys.path_hooks must be a list of "
1241 path_importer_cache
= PySys_GetObject("path_importer_cache");
1242 if (path_importer_cache
== NULL
||
1243 !PyDict_Check(path_importer_cache
)) {
1244 PyErr_SetString(PyExc_ImportError
,
1245 "sys.path_importer_cache must be a dict");
1249 npath
= PyList_Size(path
);
1250 namelen
= strlen(name
);
1251 for (i
= 0; i
< npath
; i
++) {
1252 PyObject
*copy
= NULL
;
1253 PyObject
*v
= PyList_GetItem(path
, i
);
1256 #ifdef Py_USING_UNICODE
1257 if (PyUnicode_Check(v
)) {
1258 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1259 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1266 if (!PyString_Check(v
))
1268 len
= PyString_GET_SIZE(v
);
1269 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1271 continue; /* Too long */
1273 strcpy(buf
, PyString_AS_STRING(v
));
1274 if (strlen(buf
) != len
) {
1276 continue; /* v contains '\0' */
1279 /* sys.path_hooks import hook */
1280 if (p_loader
!= NULL
) {
1283 importer
= get_path_importer(path_importer_cache
,
1285 if (importer
== NULL
) {
1289 /* Note: importer is a borrowed reference */
1290 if (importer
!= Py_None
) {
1292 loader
= PyObject_CallMethod(importer
,
1297 return NULL
; /* error */
1298 if (loader
!= Py_None
) {
1299 /* a loader was found */
1301 return &importhookdescr
;
1307 /* no hook was found, use builtin import */
1309 if (len
> 0 && buf
[len
-1] != SEP
1311 && buf
[len
-1] != ALTSEP
1315 strcpy(buf
+len
, name
);
1318 /* Check for package import (buf holds a directory name,
1319 and there's an __init__ module in that directory */
1321 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1322 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1323 case_ok(buf
, len
, namelen
, name
)) { /* case matches */
1324 if (find_init_module(buf
)) { /* and has __init__.py */
1329 char warnstr
[MAXPATHLEN
+80];
1330 sprintf(warnstr
, "Not importing directory "
1331 "'%.*s': missing __init__.py",
1333 if (PyErr_Warn(PyExc_ImportWarning
,
1341 /* XXX How are you going to test for directories? */
1344 case_ok(buf
, len
, namelen
, name
)) {
1345 if (find_init_module(buf
)) {
1350 char warnstr
[MAXPATHLEN
+80];
1351 sprintf(warnstr
, "Not importing directory "
1352 "'%.*s': missing __init__.py",
1354 if (PyErr_Warn(PyExc_ImportWarning
,
1362 #if defined(PYOS_OS2)
1363 /* take a snapshot of the module spec for restoration
1364 * after the 8 character DLL hackery
1366 saved_buf
= strdup(buf
);
1368 saved_namelen
= namelen
;
1369 #endif /* PYOS_OS2 */
1370 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1371 #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
1372 /* OS/2 limits DLLs to 8 character names (w/o
1374 * so if the name is longer than that and its a
1375 * dynamically loaded module we're going to try,
1376 * truncate the name before trying
1378 if (strlen(subname
) > 8) {
1379 /* is this an attempt to load a C extension? */
1380 const struct filedescr
*scan
;
1381 scan
= _PyImport_DynLoadFiletab
;
1382 while (scan
->suffix
!= NULL
) {
1383 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1388 if (scan
->suffix
!= NULL
) {
1389 /* yes, so truncate the name */
1391 len
-= strlen(subname
) - namelen
;
1395 #endif /* PYOS_OS2 */
1396 strcpy(buf
+len
, fdp
->suffix
);
1397 if (Py_VerboseFlag
> 1)
1398 PySys_WriteStderr("# trying %s\n", buf
);
1399 filemode
= fdp
->mode
;
1400 if (filemode
[0] == 'U')
1401 filemode
= "r" PY_STDIOTEXTMODE
;
1402 fp
= fopen(buf
, filemode
);
1404 if (case_ok(buf
, len
, namelen
, name
))
1406 else { /* continue search */
1411 #if defined(PYOS_OS2)
1412 /* restore the saved snapshot */
1413 strcpy(buf
, saved_buf
);
1415 namelen
= saved_namelen
;
1418 #if defined(PYOS_OS2)
1419 /* don't need/want the module name snapshot anymore */
1431 PyErr_Format(PyExc_ImportError
,
1432 "No module named %.200s", name
);
1439 /* Helpers for main.c
1440 * Find the source file corresponding to a named module
1443 _PyImport_FindModule(const char *name
, PyObject
*path
, char *buf
,
1444 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1446 return find_module((char *) name
, (char *) name
, path
,
1447 buf
, buflen
, p_fp
, p_loader
);
1450 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr
* fd
)
1452 return fd
->type
== PY_SOURCE
|| fd
->type
== PY_COMPILED
;
1455 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1456 * The arguments here are tricky, best shown by example:
1457 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1459 * |--------------------- buf ---------------------|
1460 * |------------------- len ------------------|
1461 * |------ name -------|
1462 * |----- namelen -----|
1463 * buf is the full path, but len only counts up to (& exclusive of) the
1464 * extension. name is the module name, also exclusive of extension.
1466 * We've already done a successful stat() or fopen() on buf, so know that
1467 * there's some match, possibly case-insensitive.
1469 * case_ok() is to return 1 if there's a case-sensitive match for
1470 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1473 * case_ok() is used to implement case-sensitive import semantics even
1474 * on platforms with case-insensitive filesystems. It's trivial to implement
1475 * for case-sensitive filesystems. It's pretty much a cross-platform
1476 * nightmare for systems with case-insensitive filesystems.
1479 /* First we may need a pile of platform-specific header files; the sequence
1480 * of #if's here should match the sequence in the body of case_ok().
1482 #if defined(MS_WINDOWS)
1483 #include <windows.h>
1485 #elif defined(DJGPP)
1488 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1489 #include <sys/types.h>
1492 #elif defined(PYOS_OS2)
1494 #define INCL_DOSERRORS
1495 #define INCL_NOPMAPI
1498 #elif defined(RISCOS)
1499 #include "oslib/osfscontrol.h"
1503 case_ok(char *buf
, Py_ssize_t len
, Py_ssize_t namelen
, char *name
)
1505 /* Pick a platform-specific implementation; the sequence of #if's here should
1506 * match the sequence just above.
1510 #if defined(MS_WINDOWS)
1511 WIN32_FIND_DATA data
;
1514 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1517 h
= FindFirstFile(buf
, &data
);
1518 if (h
== INVALID_HANDLE_VALUE
) {
1519 PyErr_Format(PyExc_NameError
,
1520 "Can't find file for module %.100s\n(filename %.300s)",
1525 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1528 #elif defined(DJGPP)
1532 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1535 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1537 PyErr_Format(PyExc_NameError
,
1538 "Can't find file for module %.100s\n(filename %.300s)",
1542 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1544 /* new-fangled macintosh (macosx) or Cygwin */
1545 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1548 char dirname
[MAXPATHLEN
+ 1];
1549 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1551 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1554 /* Copy the dir component into dirname; substitute "." if empty */
1560 assert(dirlen
<= MAXPATHLEN
);
1561 memcpy(dirname
, buf
, dirlen
);
1562 dirname
[dirlen
] = '\0';
1564 /* Open the directory and search the entries for an exact match. */
1565 dirp
= opendir(dirname
);
1567 char *nameWithExt
= buf
+ len
- namelen
;
1568 while ((dp
= readdir(dirp
)) != NULL
) {
1570 #ifdef _DIRENT_HAVE_D_NAMELEN
1575 if (thislen
>= namelen
&&
1576 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1577 (void)closedir(dirp
);
1578 return 1; /* Found */
1581 (void)closedir(dirp
);
1583 return 0 ; /* Not found */
1586 #elif defined(RISCOS)
1587 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1588 char buf2
[MAXPATHLEN
+2];
1589 char *nameWithExt
= buf
+len
-namelen
;
1593 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1597 append wildcard, otherwise case of filename wouldn't be touched */
1601 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1602 canonlen
= MAXPATHLEN
+1-canonlen
;
1603 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1605 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1606 return 1; /* match */
1611 #elif defined(PYOS_OS2)
1617 if (getenv("PYTHONCASEOK") != NULL
)
1620 rc
= DosFindFirst(buf
,
1622 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1623 &ffbuf
, sizeof(ffbuf
),
1628 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1630 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1639 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1641 find_init_module(char *buf
)
1643 const size_t save_len
= strlen(buf
);
1644 size_t i
= save_len
;
1645 char *pname
; /* pointer to start of __init__ */
1646 struct stat statbuf
;
1648 /* For calling case_ok(buf, len, namelen, name):
1649 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1651 * |--------------------- buf ---------------------|
1652 * |------------------- len ------------------|
1653 * |------ name -------|
1654 * |----- namelen -----|
1656 if (save_len
+ 13 >= MAXPATHLEN
)
1660 strcpy(pname
, "__init__.py");
1661 if (stat(buf
, &statbuf
) == 0) {
1663 save_len
+ 9, /* len("/__init__") */
1664 8, /* len("__init__") */
1666 buf
[save_len
] = '\0';
1671 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1672 if (stat(buf
, &statbuf
) == 0) {
1674 save_len
+ 9, /* len("/__init__") */
1675 8, /* len("__init__") */
1677 buf
[save_len
] = '\0';
1681 buf
[save_len
] = '\0';
1689 find_init_module(buf
)
1692 int save_len
= strlen(buf
);
1695 if (save_len
+ 13 >= MAXPATHLEN
)
1698 strcpy(buf
+i
, "__init__/py");
1700 buf
[save_len
] = '\0';
1704 if (Py_OptimizeFlag
)
1709 buf
[save_len
] = '\0';
1712 buf
[save_len
] = '\0';
1717 #endif /* HAVE_STAT */
1720 static int init_builtin(char *); /* Forward */
1722 /* Load an external module using the default search path and return
1723 its module object WITH INCREMENTED REFERENCE COUNT */
1726 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1732 /* First check that there's an open file (if we need one) */
1737 PyErr_Format(PyExc_ValueError
,
1738 "file object required for import (type code %d)",
1747 m
= load_source_module(name
, buf
, fp
);
1751 m
= load_compiled_module(name
, buf
, fp
);
1754 #ifdef HAVE_DYNAMIC_LOADING
1756 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1761 m
= load_package(name
, buf
);
1766 if (buf
!= NULL
&& buf
[0] != '\0')
1768 if (type
== C_BUILTIN
)
1769 err
= init_builtin(name
);
1771 err
= PyImport_ImportFrozenModule(name
);
1775 PyErr_Format(PyExc_ImportError
,
1776 "Purported %s module %.200s not found",
1778 "builtin" : "frozen",
1782 modules
= PyImport_GetModuleDict();
1783 m
= PyDict_GetItemString(modules
, name
);
1787 "%s module %.200s not properly initialized",
1789 "builtin" : "frozen",
1797 if (loader
== NULL
) {
1798 PyErr_SetString(PyExc_ImportError
,
1799 "import hook without loader");
1802 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1807 PyErr_Format(PyExc_ImportError
,
1808 "Don't know how to import %.200s (type code %d)",
1818 /* Initialize a built-in module.
1819 Return 1 for success, 0 if the module is not found, and -1 with
1820 an exception set if the initialization failed. */
1823 init_builtin(char *name
)
1827 if (_PyImport_FindExtension(name
, name
) != NULL
)
1830 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1831 if (strcmp(name
, p
->name
) == 0) {
1832 if (p
->initfunc
== NULL
) {
1833 PyErr_Format(PyExc_ImportError
,
1834 "Cannot re-init internal module %.200s",
1839 PySys_WriteStderr("import %s # builtin\n", name
);
1841 if (PyErr_Occurred())
1843 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1852 /* Frozen modules */
1854 static struct _frozen
*
1855 find_frozen(char *name
)
1859 for (p
= PyImport_FrozenModules
; ; p
++) {
1860 if (p
->name
== NULL
)
1862 if (strcmp(p
->name
, name
) == 0)
1869 get_frozen_object(char *name
)
1871 struct _frozen
*p
= find_frozen(name
);
1875 PyErr_Format(PyExc_ImportError
,
1876 "No such frozen object named %.200s",
1880 if (p
->code
== NULL
) {
1881 PyErr_Format(PyExc_ImportError
,
1882 "Excluded frozen object named %.200s",
1889 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1892 /* Initialize a frozen module.
1893 Return 1 for succes, 0 if the module is not found, and -1 with
1894 an exception set if the initialization failed.
1895 This function is also used from frozenmain.c */
1898 PyImport_ImportFrozenModule(char *name
)
1900 struct _frozen
*p
= find_frozen(name
);
1908 if (p
->code
== NULL
) {
1909 PyErr_Format(PyExc_ImportError
,
1910 "Excluded frozen object named %.200s",
1915 ispackage
= (size
< 0);
1919 PySys_WriteStderr("import %s # frozen%s\n",
1920 name
, ispackage
? " package" : "");
1921 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1924 if (!PyCode_Check(co
)) {
1925 PyErr_Format(PyExc_TypeError
,
1926 "frozen object %.200s is not a code object",
1931 /* Set __path__ to the package name */
1934 m
= PyImport_AddModule(name
);
1937 d
= PyModule_GetDict(m
);
1938 s
= PyString_InternFromString(name
);
1941 err
= PyDict_SetItemString(d
, "__path__", s
);
1946 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1958 /* Import a module, either built-in, frozen, or external, and return
1959 its module object WITH INCREMENTED REFERENCE COUNT */
1962 PyImport_ImportModule(const char *name
)
1967 pname
= PyString_FromString(name
);
1970 result
= PyImport_Import(pname
);
1975 /* Forward declarations for helper routines */
1976 static PyObject
*get_parent(PyObject
*globals
, char *buf
,
1977 Py_ssize_t
*p_buflen
, int level
);
1978 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1979 char **p_name
, char *buf
, Py_ssize_t
*p_buflen
);
1980 static int mark_miss(char *name
);
1981 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1982 char *buf
, Py_ssize_t buflen
, int recursive
);
1983 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1985 /* The Magnum Opus of dotted-name import :-) */
1988 import_module_level(char *name
, PyObject
*globals
, PyObject
*locals
,
1989 PyObject
*fromlist
, int level
)
1991 char buf
[MAXPATHLEN
+1];
1992 Py_ssize_t buflen
= 0;
1993 PyObject
*parent
, *head
, *next
, *tail
;
1995 parent
= get_parent(globals
, buf
, &buflen
, level
);
1999 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
2006 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
2014 if (tail
== Py_None
) {
2015 /* If tail is Py_None, both get_parent and load_next found
2016 an empty module name: someone called __import__("") or
2017 doctored faulty bytecode */
2020 PyErr_SetString(PyExc_ValueError
,
2021 "Empty module name");
2025 if (fromlist
!= NULL
) {
2026 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
2030 if (fromlist
== NULL
) {
2036 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
2044 /* For DLL compatibility */
2045 #undef PyImport_ImportModuleEx
2047 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
2052 result
= import_module_level(name
, globals
, locals
, fromlist
, -1);
2053 if (unlock_import() < 0) {
2055 PyErr_SetString(PyExc_RuntimeError
,
2056 "not holding the import lock");
2061 #define PyImport_ImportModuleEx(n, g, l, f) \
2062 PyImport_ImportModuleLevel(n, g, l, f, -1);
2065 PyImport_ImportModuleLevel(char *name
, PyObject
*globals
, PyObject
*locals
,
2066 PyObject
*fromlist
, int level
)
2070 result
= import_module_level(name
, globals
, locals
, fromlist
, level
);
2071 if (unlock_import() < 0) {
2073 PyErr_SetString(PyExc_RuntimeError
,
2074 "not holding the import lock");
2080 /* Return the package that an import is being performed in. If globals comes
2081 from the module foo.bar.bat (not itself a package), this returns the
2082 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2083 the package's entry in sys.modules is returned, as a borrowed reference.
2085 The *name* of the returned package is returned in buf, with the length of
2086 the name in *p_buflen.
2088 If globals doesn't come from a package or a module in a package, or a
2089 corresponding entry is not found in sys.modules, Py_None is returned.
2092 get_parent(PyObject
*globals
, char *buf
, Py_ssize_t
*p_buflen
, int level
)
2094 static PyObject
*namestr
= NULL
;
2095 static PyObject
*pathstr
= NULL
;
2096 PyObject
*modname
, *modpath
, *modules
, *parent
;
2098 if (globals
== NULL
|| !PyDict_Check(globals
) || !level
)
2101 if (namestr
== NULL
) {
2102 namestr
= PyString_InternFromString("__name__");
2103 if (namestr
== NULL
)
2106 if (pathstr
== NULL
) {
2107 pathstr
= PyString_InternFromString("__path__");
2108 if (pathstr
== NULL
)
2114 modname
= PyDict_GetItem(globals
, namestr
);
2115 if (modname
== NULL
|| !PyString_Check(modname
))
2118 modpath
= PyDict_GetItem(globals
, pathstr
);
2119 if (modpath
!= NULL
) {
2120 Py_ssize_t len
= PyString_GET_SIZE(modname
);
2121 if (len
> MAXPATHLEN
) {
2122 PyErr_SetString(PyExc_ValueError
,
2123 "Module name too long");
2126 strcpy(buf
, PyString_AS_STRING(modname
));
2129 char *start
= PyString_AS_STRING(modname
);
2130 char *lastdot
= strrchr(start
, '.');
2132 if (lastdot
== NULL
&& level
> 0) {
2133 PyErr_SetString(PyExc_ValueError
,
2134 "Attempted relative import in non-package");
2137 if (lastdot
== NULL
)
2139 len
= lastdot
- start
;
2140 if (len
>= MAXPATHLEN
) {
2141 PyErr_SetString(PyExc_ValueError
,
2142 "Module name too long");
2145 strncpy(buf
, start
, len
);
2149 while (--level
> 0) {
2150 char *dot
= strrchr(buf
, '.');
2152 PyErr_SetString(PyExc_ValueError
,
2153 "Attempted relative import beyond "
2154 "toplevel package");
2159 *p_buflen
= strlen(buf
);
2161 modules
= PyImport_GetModuleDict();
2162 parent
= PyDict_GetItemString(modules
, buf
);
2164 PyErr_Format(PyExc_SystemError
,
2165 "Parent module '%.200s' not loaded", buf
);
2167 /* We expect, but can't guarantee, if parent != None, that:
2168 - parent.__name__ == buf
2169 - parent.__dict__ is globals
2170 If this is violated... Who cares? */
2173 /* altmod is either None or same as mod */
2175 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2176 Py_ssize_t
*p_buflen
)
2178 char *name
= *p_name
;
2179 char *dot
= strchr(name
, '.');
2184 if (strlen(name
) == 0) {
2185 /* completely empty module name should only happen in
2186 'from . import' (or '__import__("")')*/
2201 PyErr_SetString(PyExc_ValueError
,
2202 "Empty module name");
2206 p
= buf
+ *p_buflen
;
2209 if (p
+len
-buf
>= MAXPATHLEN
) {
2210 PyErr_SetString(PyExc_ValueError
,
2211 "Module name too long");
2214 strncpy(p
, name
, len
);
2216 *p_buflen
= p
+len
-buf
;
2218 result
= import_submodule(mod
, p
, buf
);
2219 if (result
== Py_None
&& altmod
!= mod
) {
2221 /* Here, altmod must be None and mod must not be None */
2222 result
= import_submodule(altmod
, p
, p
);
2223 if (result
!= NULL
&& result
!= Py_None
) {
2224 if (mark_miss(buf
) != 0) {
2228 strncpy(buf
, name
, len
);
2236 if (result
== Py_None
) {
2238 PyErr_Format(PyExc_ImportError
,
2239 "No module named %.200s", name
);
2247 mark_miss(char *name
)
2249 PyObject
*modules
= PyImport_GetModuleDict();
2250 return PyDict_SetItemString(modules
, name
, Py_None
);
2254 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, Py_ssize_t buflen
,
2259 if (!PyObject_HasAttrString(mod
, "__path__"))
2262 for (i
= 0; ; i
++) {
2263 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2266 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2272 if (!PyString_Check(item
)) {
2273 PyErr_SetString(PyExc_TypeError
,
2274 "Item in ``from list'' not a string");
2278 if (PyString_AS_STRING(item
)[0] == '*') {
2281 /* See if the package defines __all__ */
2283 continue; /* Avoid endless recursion */
2284 all
= PyObject_GetAttrString(mod
, "__all__");
2288 int ret
= ensure_fromlist(mod
, all
, buf
, buflen
, 1);
2295 hasit
= PyObject_HasAttr(mod
, item
);
2297 char *subname
= PyString_AS_STRING(item
);
2300 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2301 PyErr_SetString(PyExc_ValueError
,
2302 "Module name too long");
2309 submod
= import_submodule(mod
, subname
, buf
);
2311 if (submod
== NULL
) {
2323 add_submodule(PyObject
*mod
, PyObject
*submod
, char *fullname
, char *subname
,
2328 /* Irrespective of the success of this load, make a
2329 reference to it in the parent package module. A copy gets
2330 saved in the modules dictionary under the full name, so get a
2331 reference from there, if need be. (The exception is when the
2332 load failed with a SyntaxError -- then there's no trace in
2333 sys.modules. In that case, of course, do nothing extra.) */
2334 if (submod
== NULL
) {
2335 submod
= PyDict_GetItemString(modules
, fullname
);
2339 if (PyModule_Check(mod
)) {
2340 /* We can't use setattr here since it can give a
2341 * spurious warning if the submodule name shadows a
2343 PyObject
*dict
= PyModule_GetDict(mod
);
2346 if (PyDict_SetItemString(dict
, subname
, submod
) < 0)
2350 if (PyObject_SetAttrString(mod
, subname
, submod
) < 0)
2357 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2359 PyObject
*modules
= PyImport_GetModuleDict();
2363 if mod == None: subname == fullname
2364 else: mod.__name__ + "." + subname == fullname
2367 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2371 PyObject
*path
, *loader
= NULL
;
2372 char buf
[MAXPATHLEN
+1];
2373 struct filedescr
*fdp
;
2379 path
= PyObject_GetAttrString(mod
, "__path__");
2388 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2392 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2398 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2402 if (!add_submodule(mod
, m
, fullname
, subname
, modules
)) {
2412 /* Re-import a module of any kind and return its module object, WITH
2413 INCREMENTED REFERENCE COUNT */
2416 PyImport_ReloadModule(PyObject
*m
)
2418 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
2419 PyObject
*modules_reloading
= interp
->modules_reloading
;
2420 PyObject
*modules
= PyImport_GetModuleDict();
2421 PyObject
*path
= NULL
, *loader
= NULL
, *existing_m
= NULL
;
2422 char *name
, *subname
;
2423 char buf
[MAXPATHLEN
+1];
2424 struct filedescr
*fdp
;
2428 if (modules_reloading
== NULL
) {
2429 Py_FatalError("PyImport_ReloadModule: "
2430 "no modules_reloading dictionary!");
2434 if (m
== NULL
|| !PyModule_Check(m
)) {
2435 PyErr_SetString(PyExc_TypeError
,
2436 "reload() argument must be module");
2439 name
= PyModule_GetName(m
);
2442 if (m
!= PyDict_GetItemString(modules
, name
)) {
2443 PyErr_Format(PyExc_ImportError
,
2444 "reload(): module %.200s not in sys.modules",
2448 existing_m
= PyDict_GetItemString(modules_reloading
, name
);
2449 if (existing_m
!= NULL
) {
2450 /* Due to a recursive reload, this module is already
2452 Py_INCREF(existing_m
);
2455 if (PyDict_SetItemString(modules_reloading
, name
, m
) < 0)
2458 subname
= strrchr(name
, '.');
2459 if (subname
== NULL
)
2462 PyObject
*parentname
, *parent
;
2463 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2464 if (parentname
== NULL
) {
2465 imp_modules_reloading_clear();
2468 parent
= PyDict_GetItem(modules
, parentname
);
2469 if (parent
== NULL
) {
2470 PyErr_Format(PyExc_ImportError
,
2471 "reload(): parent %.200s not in sys.modules",
2472 PyString_AS_STRING(parentname
));
2473 Py_DECREF(parentname
);
2474 imp_modules_reloading_clear();
2477 Py_DECREF(parentname
);
2479 path
= PyObject_GetAttrString(parent
, "__path__");
2484 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, &loader
);
2489 imp_modules_reloading_clear();
2493 newm
= load_module(name
, fp
, buf
, fdp
->type
, loader
);
2499 /* load_module probably removed name from modules because of
2500 * the error. Put back the original module object. We're
2501 * going to return NULL in this case regardless of whether
2502 * replacing name succeeds, so the return value is ignored.
2504 PyDict_SetItemString(modules
, name
, m
);
2506 imp_modules_reloading_clear();
2511 /* Higher-level import emulator which emulates the "import" statement
2512 more accurately -- it invokes the __import__() function from the
2513 builtins of the current globals. This means that the import is
2514 done using whatever import hooks are installed in the current
2515 environment, e.g. by "rexec".
2516 A dummy list ["__doc__"] is passed as the 4th argument so that
2517 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2518 will return <module "gencache"> instead of <module "win32com">. */
2521 PyImport_Import(PyObject
*module_name
)
2523 static PyObject
*silly_list
= NULL
;
2524 static PyObject
*builtins_str
= NULL
;
2525 static PyObject
*import_str
= NULL
;
2526 PyObject
*globals
= NULL
;
2527 PyObject
*import
= NULL
;
2528 PyObject
*builtins
= NULL
;
2531 /* Initialize constant string objects */
2532 if (silly_list
== NULL
) {
2533 import_str
= PyString_InternFromString("__import__");
2534 if (import_str
== NULL
)
2536 builtins_str
= PyString_InternFromString("__builtins__");
2537 if (builtins_str
== NULL
)
2539 silly_list
= Py_BuildValue("[s]", "__doc__");
2540 if (silly_list
== NULL
)
2544 /* Get the builtins from current globals */
2545 globals
= PyEval_GetGlobals();
2546 if (globals
!= NULL
) {
2548 builtins
= PyObject_GetItem(globals
, builtins_str
);
2549 if (builtins
== NULL
)
2553 /* No globals -- use standard builtins, and fake globals */
2556 builtins
= PyImport_ImportModuleLevel("__builtin__",
2557 NULL
, NULL
, NULL
, 0);
2558 if (builtins
== NULL
)
2560 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2561 if (globals
== NULL
)
2565 /* Get the __import__ function from the builtins */
2566 if (PyDict_Check(builtins
)) {
2567 import
= PyObject_GetItem(builtins
, import_str
);
2569 PyErr_SetObject(PyExc_KeyError
, import_str
);
2572 import
= PyObject_GetAttr(builtins
, import_str
);
2576 /* Call the __import__ function with the proper argument list */
2577 r
= PyObject_CallFunctionObjArgs(import
, module_name
, globals
,
2578 globals
, silly_list
, NULL
);
2581 Py_XDECREF(globals
);
2582 Py_XDECREF(builtins
);
2589 /* Module 'imp' provides Python access to the primitives used for
2594 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2598 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2599 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2600 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2601 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2603 return PyString_FromStringAndSize(buf
, 4);
2607 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2610 struct filedescr
*fdp
;
2612 list
= PyList_New(0);
2615 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2616 PyObject
*item
= Py_BuildValue("ssi",
2617 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2622 if (PyList_Append(list
, item
) < 0) {
2633 call_find_module(char *name
, PyObject
*path
)
2635 extern int fclose(FILE *);
2636 PyObject
*fob
, *ret
;
2637 struct filedescr
*fdp
;
2638 char pathname
[MAXPATHLEN
+1];
2642 if (path
== Py_None
)
2644 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2648 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2658 ret
= Py_BuildValue("Os(ssi)",
2659 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2665 imp_find_module(PyObject
*self
, PyObject
*args
)
2668 PyObject
*path
= NULL
;
2669 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2671 return call_find_module(name
, path
);
2675 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2680 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2682 ret
= init_builtin(name
);
2689 m
= PyImport_AddModule(name
);
2695 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2700 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2702 ret
= PyImport_ImportFrozenModule(name
);
2709 m
= PyImport_AddModule(name
);
2715 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2719 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2721 return get_frozen_object(name
);
2725 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2728 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2730 return PyInt_FromLong(is_builtin(name
));
2734 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2738 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2740 p
= find_frozen(name
);
2741 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2745 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2750 mode
= "r" PY_STDIOTEXTMODE
;
2751 fp
= fopen(pathname
, mode
);
2753 PyErr_SetFromErrno(PyExc_IOError
);
2756 fp
= PyFile_AsFile(fob
);
2758 PyErr_SetString(PyExc_ValueError
,
2759 "bad/closed file object");
2765 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2769 PyObject
*fob
= NULL
;
2772 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2773 &PyFile_Type
, &fob
))
2775 fp
= get_file(pathname
, fob
, "rb");
2778 m
= load_compiled_module(name
, pathname
, fp
);
2784 #ifdef HAVE_DYNAMIC_LOADING
2787 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2791 PyObject
*fob
= NULL
;
2794 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2795 &PyFile_Type
, &fob
))
2798 fp
= get_file(pathname
, fob
, "r");
2802 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2806 #endif /* HAVE_DYNAMIC_LOADING */
2809 imp_load_source(PyObject
*self
, PyObject
*args
)
2813 PyObject
*fob
= NULL
;
2816 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2817 &PyFile_Type
, &fob
))
2819 fp
= get_file(pathname
, fob
, "r");
2822 m
= load_source_module(name
, pathname
, fp
);
2829 imp_load_module(PyObject
*self
, PyObject
*args
)
2834 char *suffix
; /* Unused */
2839 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2840 &name
, &fob
, &pathname
,
2841 &suffix
, &mode
, &type
))
2844 /* Mode must start with 'r' or 'U' and must not contain '+'.
2845 Implicit in this test is the assumption that the mode
2846 may contain other modifiers like 'b' or 't'. */
2848 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2849 PyErr_Format(PyExc_ValueError
,
2850 "invalid file open mode %.200s", mode
);
2857 if (!PyFile_Check(fob
)) {
2858 PyErr_SetString(PyExc_ValueError
,
2859 "load_module arg#2 should be a file or None");
2862 fp
= get_file(pathname
, fob
, mode
);
2866 return load_module(name
, fp
, pathname
, type
, NULL
);
2870 imp_load_package(PyObject
*self
, PyObject
*args
)
2874 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2876 return load_package(name
, pathname
);
2880 imp_new_module(PyObject
*self
, PyObject
*args
)
2883 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2885 return PyModule_New(name
);
2890 PyDoc_STRVAR(doc_imp
,
2891 "This module provides the components needed to build your own\n\
2892 __import__ function. Undocumented functions are obsolete.");
2894 PyDoc_STRVAR(doc_find_module
,
2895 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2896 Search for a module. If path is omitted or None, search for a\n\
2897 built-in, frozen or special module and continue search in sys.path.\n\
2898 The module name cannot contain '.'; to search for a submodule of a\n\
2899 package, pass the submodule name and the package's __path__.");
2901 PyDoc_STRVAR(doc_load_module
,
2902 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2903 Load a module, given information returned by find_module().\n\
2904 The module name must include the full package name, if any.");
2906 PyDoc_STRVAR(doc_get_magic
,
2907 "get_magic() -> string\n\
2908 Return the magic number for .pyc or .pyo files.");
2910 PyDoc_STRVAR(doc_get_suffixes
,
2911 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2912 Return a list of (suffix, mode, type) tuples describing the files\n\
2913 that find_module() looks for.");
2915 PyDoc_STRVAR(doc_new_module
,
2916 "new_module(name) -> module\n\
2917 Create a new module. Do not enter it in sys.modules.\n\
2918 The module name must include the full package name, if any.");
2920 PyDoc_STRVAR(doc_lock_held
,
2921 "lock_held() -> boolean\n\
2922 Return True if the import lock is currently held, else False.\n\
2923 On platforms without threads, return False.");
2925 PyDoc_STRVAR(doc_acquire_lock
,
2926 "acquire_lock() -> None\n\
2927 Acquires the interpreter's import lock for the current thread.\n\
2928 This lock should be used by import hooks to ensure thread-safety\n\
2929 when importing modules.\n\
2930 On platforms without threads, this function does nothing.");
2932 PyDoc_STRVAR(doc_release_lock
,
2933 "release_lock() -> None\n\
2934 Release the interpreter's import lock.\n\
2935 On platforms without threads, this function does nothing.");
2937 static PyMethodDef imp_methods
[] = {
2938 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2939 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
2940 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
2941 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2942 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2943 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
2944 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
2945 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
2946 /* The rest are obsolete */
2947 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2948 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2949 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2950 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2951 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2952 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2953 #ifdef HAVE_DYNAMIC_LOADING
2954 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2956 {"load_package", imp_load_package
, METH_VARARGS
},
2957 {"load_source", imp_load_source
, METH_VARARGS
},
2958 {NULL
, NULL
} /* sentinel */
2962 setint(PyObject
*d
, char *name
, int value
)
2967 v
= PyInt_FromLong((long)value
);
2968 err
= PyDict_SetItemString(d
, name
, v
);
2978 NullImporter_init(NullImporter
*self
, PyObject
*args
, PyObject
*kwds
)
2982 if (!_PyArg_NoKeywords("NullImporter()", kwds
))
2985 if (!PyArg_ParseTuple(args
, "s:NullImporter",
2989 if (strlen(path
) == 0) {
2990 PyErr_SetString(PyExc_ImportError
, "empty pathname");
2994 struct stat statbuf
;
2997 rv
= stat(path
, &statbuf
);
3000 if (S_ISDIR(statbuf
.st_mode
)) {
3001 /* it's a directory */
3002 PyErr_SetString(PyExc_ImportError
,
3003 "existing directory");
3008 if (object_exists(path
)) {
3011 /* it's a directory */
3012 PyErr_SetString(PyExc_ImportError
,
3013 "existing directory");
3023 NullImporter_find_module(NullImporter
*self
, PyObject
*args
)
3028 static PyMethodDef NullImporter_methods
[] = {
3029 {"find_module", (PyCFunction
)NullImporter_find_module
, METH_VARARGS
,
3030 "Always return None"
3032 {NULL
} /* Sentinel */
3036 static PyTypeObject NullImporterType
= {
3037 PyVarObject_HEAD_INIT(NULL
, 0)
3038 "imp.NullImporter", /*tp_name*/
3039 sizeof(NullImporter
), /*tp_basicsize*/
3048 0, /*tp_as_sequence*/
3049 0, /*tp_as_mapping*/
3056 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
3057 "Null importer object", /* tp_doc */
3058 0, /* tp_traverse */
3060 0, /* tp_richcompare */
3061 0, /* tp_weaklistoffset */
3063 0, /* tp_iternext */
3064 NullImporter_methods
, /* tp_methods */
3069 0, /* tp_descr_get */
3070 0, /* tp_descr_set */
3071 0, /* tp_dictoffset */
3072 (initproc
)NullImporter_init
, /* tp_init */
3074 PyType_GenericNew
/* tp_new */
3083 if (PyType_Ready(&NullImporterType
) < 0)
3086 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
3087 NULL
, PYTHON_API_VERSION
);
3090 d
= PyModule_GetDict(m
);
3094 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
3095 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
3096 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
3097 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
3098 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
3099 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
3100 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
3101 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
3102 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
3103 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
3105 Py_INCREF(&NullImporterType
);
3106 PyModule_AddObject(m
, "NullImporter", (PyObject
*)&NullImporterType
);
3112 /* API for embedding applications that want to add their own entries
3113 to the table of built-in modules. This should normally be called
3114 *before* Py_Initialize(). When the table resize fails, -1 is
3115 returned and the existing table is unchanged.
3117 After a similar function by Just van Rossum. */
3120 PyImport_ExtendInittab(struct _inittab
*newtab
)
3122 static struct _inittab
*our_copy
= NULL
;
3126 /* Count the number of entries in both tables */
3127 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
3130 return 0; /* Nothing to do */
3131 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
3134 /* Allocate new memory for the combined table */
3136 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
3140 /* Copy the tables into the new memory */
3141 if (our_copy
!= PyImport_Inittab
)
3142 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
3143 PyImport_Inittab
= our_copy
= p
;
3144 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
3149 /* Shorthand to add a single entry given a name and a function */
3152 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
3154 struct _inittab newtab
[2];
3156 memset(newtab
, '\0', sizeof newtab
);
3158 newtab
[0].name
= name
;
3159 newtab
[0].initfunc
= initfunc
;
3161 return PyImport_ExtendInittab(newtab
);