This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Decorater
Recipients Decorater, paul.moore, steve.dower, tim.golden, zach.ware
Date 2016-11-28.09:45:39
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1480326340.52.0.39566018579.issue28816@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2016-11-28 09:45:40Decoratersetrecipients: + Decorater, paul.moore, tim.golden, zach.ware, steve.dower
2016-11-28 09:45:40Decoratersetmessageid: <1480326340.52.0.39566018579.issue28816@psf.upfronthosting.co.za>
2016-11-28 09:45:40Decoraterlinkissue28816 messages
2016-11-28 09:45:39Decoratercreate