2 Import hooks; when installed with the install() function, these hooks
3 allow importing .pyx files as if they were Python modules.
5 If you want the hook installed every time you run Python
6 you can add it to your Python version by adding these lines to
7 sitecustomize.py (which you can create from scratch in site-packages
8 if it doesn't exist there or somewhere else on your python path)::
13 For instance on the Mac with a non-system Python 2.3, you could create
14 sitecustomize.py with only those two lines at
15 /usr/local/lib/python2.3/site-packages/sitecustomize.py .
17 A custom distutils.core.Extension instance and setup() args
18 (Distribution) for for the build can be defined by a <modulename>.pyxbld
22 def make_ext(modname, pyxfilename):
23 from distutils.extension import Extension
24 return Extension(name = modname,
25 sources=[pyxfilename, 'hello.c'],
26 include_dirs=['/myinclude'] )
27 def make_setup_args():
28 return dict(script_args=["--compiler=mingw32"])
30 Extra dependencies can be defined by a <modulename>.pyxdep .
33 Since Cython 0.11, the :mod:`pyximport` module also has experimental
34 compilation support for normal Python modules. This allows you to
35 automatically run Cython on every .pyx and .py module that Python
36 imports, including parts of the standard library and installed
37 packages. Cython will still fail to compile a lot of Python modules,
38 in which case the import mechanism will fall back to loading the
39 Python source modules instead. The .py import mechanism is installed
42 pyximport.install(pyimport = True)
44 Running this module as a top-level script will run a test and then print
47 This code is based on the Py2.3+ import protocol as described in PEP 302.
55 mod_name = "pyximport"
57 assert sys.hexversion >= 0x2030000, "need Python 2.3 or later"
60 PYXDEP_EXT = ".pyxdep"
61 PYXBLD_EXT = ".pyxbld"
65 # Performance problem: for every PYX file that is imported, we will
66 # invoke the whole distutils infrastructure even if the module is
67 # already built. It might be more efficient to only do it when the
68 # mod time of the .pyx is newer than the mod time of the .so but
69 # the question is how to get distutils to tell me the name of the .so
70 # before it builds it. Maybe it is easy...but maybe the peformance
72 def _load_pyrex(name, filename):
73 "Load a pyrex file given a name and filename."
75 def get_distutils_extension(modname, pyxfilename):
79 # import md5 as hashlib
80 # extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()
81 # modname = modname + extra
82 extension_mod,setup_args = handle_special_build(modname, pyxfilename)
84 from distutils.extension import Extension
85 extension_mod = Extension(name = modname, sources=[pyxfilename])
86 return extension_mod,setup_args
88 def handle_special_build(modname, pyxfilename):
89 special_build = os.path.splitext(pyxfilename)[0] + PYXBLD_EXT
92 if os.path.exists(special_build):
95 # execfile(special_build, globls, locs)
96 # ext = locs["make_ext"](modname, pyxfilename)
97 mod = imp.load_source("XXXX", special_build, open(special_build))
98 make_ext = getattr(mod,'make_ext',None)
100 ext = make_ext(modname, pyxfilename)
101 assert ext and ext.sources, ("make_ext in %s did not return Extension"
103 make_setup_args = getattr(mod,'make_setup_args',None)
105 setup_args = make_setup_args()
106 assert isinstance(setup_args,dict), ("make_setup_args in %s did not return a dict"
108 assert set or setup_args, ("neither make_ext nor make_setup_args %s"
110 ext.sources = [os.path.join(os.path.dirname(special_build), source)
111 for source in ext.sources]
112 return ext, setup_args
114 def handle_dependencies(pyxfilename):
115 testing = '_test_files' in globals()
116 dependfile = os.path.splitext(pyxfilename)[0] + PYXDEP_EXT
118 # by default let distutils decide whether to rebuild on its own
119 # (it has a better idea of what the output file will be)
121 # but we know more about dependencies so force a rebuild if
122 # some of the dependencies are newer than the pyxfile.
123 if os.path.exists(dependfile):
124 depends = open(dependfile).readlines()
125 depends = [depend.strip() for depend in depends]
127 # gather dependencies in the "files" variable
128 # the dependency file is itself a dependency
130 for depend in depends:
131 fullpath = os.path.join(os.path.dirname(dependfile),
133 files.extend(glob.glob(fullpath))
135 # only for unit testing to see we did the right thing
137 _test_files[:] = [] #$pycheck_no
139 # if any file that the pyxfile depends upon is newer than
140 # the pyx file, 'touch' the pyx file so that distutils will
141 # be tricked into rebuilding it.
143 from distutils.dep_util import newer
144 if newer(file, pyxfilename):
145 print("Rebuilding because of ", file)
146 filetime = os.path.getmtime(file)
147 os.utime(pyxfilename, (filetime, filetime))
149 _test_files.append(file)
151 def build_module(name, pyxfilename, pyxbuild_dir=None):
152 assert os.path.exists(pyxfilename), (
153 "Path does not exist: %s" % pyxfilename)
154 handle_dependencies(pyxfilename)
156 extension_mod,setup_args = get_distutils_extension(name, pyxfilename)
157 build_in_temp=pyxargs.build_in_temp
158 sargs=pyxargs.setup_args.copy()
159 sargs.update(setup_args)
160 build_in_temp=sargs.pop('build_in_temp',build_in_temp)
163 so_path = pyxbuild.pyx_to_dll(pyxfilename, extension_mod,
164 build_in_temp=build_in_temp,
165 pyxbuild_dir=pyxbuild_dir,
167 reload_support=pyxargs.reload_support)
168 assert os.path.exists(so_path), "Cannot find: %s" % so_path
170 junkpath = os.path.join(os.path.dirname(so_path), name+"_*") #very dangerous with --inplace ?
171 junkstuff = glob.glob(junkpath)
172 for path in junkstuff:
177 print("Couldn't remove ", path)
181 def load_module(name, pyxfilename, pyxbuild_dir=None):
183 so_path = build_module(name, pyxfilename, pyxbuild_dir)
184 mod = imp.load_dynamic(name, so_path)
185 assert mod.__file__ == so_path, (mod.__file__, so_path)
188 raise ImportError("Building module failed: %s" %
189 traceback.format_exception_only(*sys.exc_info()[:2])),None,sys.exc_info()[2]
195 class PyxImporter(object):
196 """A meta-path importer for .pyx files.
198 def __init__(self, extension=PYX_EXT, pyxbuild_dir=None):
199 self.extension = extension
200 self.pyxbuild_dir = pyxbuild_dir
202 def find_module(self, fullname, package_path=None):
203 if fullname in sys.modules and not pyxargs.reload_support:
204 return None # only here when reload()
206 fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path)
207 if fp: fp.close() # Python should offer a Default-Loader to avoid this double find/open!
208 if pathname.endswith(self.extension):
209 return PyxLoader(fullname, pathname,
210 pyxbuild_dir=self.pyxbuild_dir)
211 if ty != imp.C_EXTENSION: # only when an extension, check if we have a .pyx next!
214 # find .pyx fast, when .so/.pyd exist --inplace
215 pyxpath = os.path.splitext(pathname)[0]+self.extension
216 if os.path.isfile(pyxpath):
217 return PyxLoader(fullname, pyxpath,
218 pyxbuild_dir=self.pyxbuild_dir)
220 # .so/.pyd's on PATH should not be remote from .pyx's
221 # think no need to implement PyxArgs.importer_search_remote here?
226 # searching sys.path ...
228 #if DEBUG_IMPORT: print "SEARCHING", fullname, package_path
229 if '.' in fullname: # only when package_path anyway?
230 mod_parts = fullname.split('.')
231 module_name = mod_parts[-1]
233 module_name = fullname
234 pyx_module_name = module_name + self.extension
235 # this may work, but it returns the file content, not its path
237 #pyx_source = pkgutil.get_data(package, pyx_module_name)
243 join_path = os.path.join
244 is_file = os.path.isfile
245 #is_dir = os.path.isdir
250 if is_file(path+sep+pyx_module_name):
251 return PyxLoader(fullname, join_path(path, pyx_module_name),
252 pyxbuild_dir=self.pyxbuild_dir)
254 # not found, normal package, not a .pyx file, none of our business
257 class PyImporter(PyxImporter):
258 """A meta-path importer for normal .py files.
260 def __init__(self, pyxbuild_dir=None):
261 self.super = super(PyImporter, self)
262 self.super.__init__(extension='.py', pyxbuild_dir=pyxbuild_dir)
263 self.uncompilable_modules = {}
264 self.blocked_modules = ['Cython', 'distutils.extension',
265 'distutils.sysconfig']
267 def find_module(self, fullname, package_path=None):
268 if fullname in sys.modules:
270 if fullname.startswith('Cython.'):
272 if fullname in self.blocked_modules:
273 # prevent infinite recursion
276 print("trying import of module '%s'" % fullname)
277 if fullname in self.uncompilable_modules:
278 path, last_modified = self.uncompilable_modules[fullname]
280 new_last_modified = os.stat(path).st_mtime
281 if new_last_modified > last_modified:
282 # import would fail again
285 # module is no longer where we found it, retry the import
288 self.blocked_modules.append(fullname)
290 importer = self.super.find_module(fullname, package_path)
291 if importer is not None:
293 if importer.init_path:
294 path = importer.init_path
298 print("importer found path %s" % path)
299 build_module(fullname, path,
300 pyxbuild_dir=self.pyxbuild_dir)
304 traceback.print_exc()
305 # build failed, not a compilable Python module
307 last_modified = os.stat(path).st_mtime
310 self.uncompilable_modules[fullname] = (path, last_modified)
313 self.blocked_modules.pop()
316 class PyxLoader(object):
317 def __init__(self, fullname, path, init_path=None, pyxbuild_dir=None):
318 self.fullname = fullname
319 self.path, self.init_path = path, init_path
320 self.pyxbuild_dir = pyxbuild_dir
322 def load_module(self, fullname):
323 assert self.fullname == fullname, (
324 "invalid module, expected %s, got %s" % (
325 self.fullname, fullname))
328 #print "PACKAGE", fullname
329 module = load_module(fullname, self.init_path,
331 module.__path__ = [self.path]
333 #print "MODULE", fullname
334 module = load_module(fullname, self.path,
340 class PyxArgs(object):
347 def install(pyximport=True, pyimport=False, build_dir=None, build_in_temp=True,
348 setup_args={}, reload_support=False ):
349 """Main entry point. Call this to install the .pyx import hook in
350 your meta-path for a single Python process. If you want it to be
351 installed whenever you use Python, add it to your sitecustomize
352 (as described above).
354 You can pass ``pyimport=True`` to also install the .py import hook
355 in your meta-path. Note, however, that it is highly experimental,
356 will not work for most .py files, and will therefore only slow
357 down your imports. Use at your own risk.
359 By default, compiled modules will end up in a ``.pyxbld``
360 directory in the user's home directory. Passing a different path
361 as ``build_dir`` will override this.
363 ``build_in_temp=False`` will produce the C files locally. Working
364 with complex dependencies and debugging becomes more easy. This
365 can principally interfere with existing files of the same name.
366 build_in_temp can be overriden by <modulename>.pyxbld/make_setup_args()
367 by a dict item of 'build_in_temp'
369 ``setup_args``: dict of arguments for Distribution - see
370 distutils.core.setup() . They are extended/overriden by those of
371 <modulename>.pyxbld/make_setup_args()
373 ``reload_support``: Enables support for dynamic
374 reload(<pyxmodulename>), e.g. after a change in the Cython code.
375 Additional files <so_path>.reloadNN may arise on that account, when
376 the previously loaded module file cannot be overwritten.
379 build_dir = os.path.expanduser('~/.pyxbld')
382 pyxargs = PyxArgs() #$pycheck_no
383 pyxargs.build_dir = build_dir
384 pyxargs.build_in_temp = build_in_temp
385 pyxargs.setup_args = (setup_args or {}).copy()
386 pyxargs.reload_support = reload_support
388 has_py_importer = False
389 has_pyx_importer = False
390 for importer in sys.meta_path:
391 if isinstance(importer, PyxImporter):
392 if isinstance(importer, PyImporter):
393 has_py_importer = True
395 has_pyx_importer = True
397 if pyimport and not has_py_importer:
398 importer = PyImporter(pyxbuild_dir=build_dir)
399 sys.meta_path.insert(0, importer)
401 if pyximport and not has_pyx_importer:
402 importer = PyxImporter(pyxbuild_dir=build_dir)
403 sys.meta_path.append(importer)
410 __main__.__name__ = mod_name
411 for name in dir(__main__):
412 item = getattr(__main__, name)
414 setattr(item, "__module__", mod_name)
415 except (AttributeError, TypeError):
419 if __name__ == '__main__':