|
| 1 | +""" |
| 2 | +Importing this module allows import .epy files like .py files. |
| 3 | +
|
| 4 | +The main reason for naming epython files with the .epy file extension is to |
| 5 | +avoid confusion with regular Python modules. A package may contain a number |
| 6 | +of (sub-) modules of which only some are epython extensions. |
| 7 | +
|
| 8 | +For development of epython packages, it is nevertheless very useful to import |
| 9 | +.epy files just like .pt files, which is possible by simply importing epython |
| 10 | +first. E.g. |
| 11 | +
|
| 12 | + import epython |
| 13 | + import myext # will import myext.epy |
| 14 | +
|
| 15 | +Without importing epython first, myext will not work, which helps to avoid |
| 16 | +using epython extensions as pure Python modules (which will be quite slow). |
| 17 | +""" |
| 18 | +import sys |
| 19 | +import imp |
| 20 | +from os.path import isfile, join |
| 21 | + |
| 22 | + |
| 23 | +class EPY_Importer(object): |
| 24 | + |
| 25 | + def find_module(self, fullname, path=None): |
| 26 | + name = fullname.rsplit('.', 1)[-1] |
| 27 | + for dir_path in path or sys.path: |
| 28 | + self.path = join(dir_path, name + '.epy') |
| 29 | + if isfile(self.path): |
| 30 | + self.modtype = imp.PY_SOURCE |
| 31 | + return self |
| 32 | + return None |
| 33 | + |
| 34 | + def load_module(self, fullname): |
| 35 | + if fullname in sys.modules: |
| 36 | + return sys.modules[fullname] |
| 37 | + |
| 38 | + mod = imp.new_module(fullname) |
| 39 | + mod.__file__ = self.path |
| 40 | + mod.__loader__ = self |
| 41 | + with open(self.path, 'rb') as fi: |
| 42 | + code = fi.read() |
| 43 | + |
| 44 | + exec(code, mod.__dict__) |
| 45 | + sys.modules[fullname] = mod |
| 46 | + return mod |
| 47 | + |
| 48 | + |
| 49 | +sys.meta_path.append(EPY_Importer()) |
0 commit comments