[issue28816] Document if zipimport can respect import hooks to load custom files from zip.

Decorater report at bugs.python.org
Mon Nov 28 04:45:40 EST 2016


New submission from Decorater:

I am wondering so lets say for example if I was to make a json import hook (code below):

from importlib.machinery import FileFinder
import json
import sys


class ExtensionImporter(object):
    """Base Importer Class."""
    def __init__(self, extension_list):
        self.extensions = extension_list

    def find_loader(self, name, path):
        """Filds some loaders for importing the module."""
        self.path = path
        return self

    def load_module(self, fullname):
        if fullname in sys.modules:
            return sys.modules[fullname]
        return None


class JsonImporter(ExtensionImporter):
    """JSON importer Class."""
    def __init__(self):
        super(JsonImporter, self).__init__(['.json'])

    def load_module(self, fullname):
        """Loads modules found with the extension"""
        premodule = super(JsonImporter, self).load_module(fullname)
        if premodule is None:
             with open(self.path, 'r') as f:
                module = json.load(f)
                sys.modules[fullname] = module
                return module
            raise ImportError('Couldn't open path')

extension_importers = [JsonImporter()]
hook_list = []
for importer in extension_importers:
    hook_list.append((importer.find_loader, importer.extensions))

sys.path_hooks.insert(0, FileFinder.path_hook(*hook_list))
sys.path_importer_cache.clear()


What if I had those json files in a zip file and used ZipImport on that zip file would it use that import hook that I shared above if all other import methods fail to import those json files (obvously they would fail though)?

There should be documentation to explain if it supports user created import hooks that they create using importlib.

This is because I would be very happy if zipimport supports my own import hook if any other method of importing files from that zip file fails but mine ends up working. It also allows people to load up many other formats (provided they know the format) as if it was a python script. (of if they compressed it in a custom file like for example a RAR file that WinRAR can create. And yes I would support a RARImport for rar files.

----------
components: Interpreter Core, Windows
messages: 281850
nosy: Decorater, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: Document if zipimport can respect import hooks to load custom files from zip.
versions: Python 3.4, Python 3.5, Python 3.6, Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28816>
_______________________________________


More information about the Python-bugs-list mailing list