<div dir="ltr"><div><div><div>Basically what you're after is a way to extend the default finder with a new file type. Historically you didn't want this because of the performance hit of the extra stat call to check that new file extension (this has been greatly alleviated in Python 3 through the caching of directory contents). But I would still argue that you don't necessarily want this for e.g. the stdlib or any other random project which might just happen to have a file with the same file extension as the one you want to have special support for.<br><br></div>I also don't think we want a class attribute to contains the default loaders since not everyone will want those default semantics in all cases either. Since we're diving into deep levels of customization I would askew anything that makes assumptions for what you want.<br><br></div>I think the best we could consider is making importlib.machinery._get_supported_loaders() a public API. That way you can easily construct a finder with the default loaders plus your custom ones. After that you can then provide a custom sys.path_hooks entry that recognizes the directories which contain your custom file type.<br><br></div>If that seems reasonable then feel free to open an enhancement request at <a href="http://bugs.python.org">bugs.python.org</a> to discuss the API and then we can discuss how to implement a PR for it.<br></div><br><div class="gmail_quote"><div dir="ltr">On Wed, 7 Feb 2018 at 07:04 Erik Bray <<a href="mailto:erik.m.bray@gmail.com">erik.m.bray@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hello,<br>
<br>
Brief problem statement: Let's say I have a custom file type (say,<br>
with extension .foo) and these .foo files are included in a package<br>
(along with other Python modules with standard extensions like .py and<br>
.so), and I want to make these .foo files importable like any other<br>
module.<br>
<br>
On its face, importlib.machinery.FileFinder makes this easy. I make a<br>
loader for my custom file type (say, FooSourceLoader), and I can use<br>
the FileFinder.path_hook helper like:<br>
<br>
sys.path_hooks.insert(0, FileFinder.path_hook((FooSourceLoader, ['.foo'])))<br>
sys.path_importer_cache.clear()<br>
<br>
Great--now I can import my .foo modules like any other Python module.<br>
However, any standard Python modules now cannot be imported. The way<br>
PathFinder sys.meta_path hook works, sys.path_hooks entries are<br>
first-come-first-serve, and furthermore FileFinder.path_hook is very<br>
promiscuous--it will take over module loading for *any* directory on<br>
sys.path, regardless what the file extensions are in that directory.<br>
So although this mechanism is provided by the stdlib, it can't really<br>
be used for this purpose without breaking imports of normal modules<br>
(and maybe it's not intended for that purpose, but the documentation<br>
is unclear).<br>
<br>
There are a number of different ways one could get around this. One<br>
might be to pass FileFinder.path_hook loaders/extension pairs for all<br>
the basic file types known by the Python interpreter. Unfortunately<br>
there's no great way to get that information. *I* know that I want to<br>
support .py, .pyc, .so etc. files, and I know which loaders to use for<br>
them. But that's really information that should belong to the Python<br>
interpreter, and not something that should be reverse-engineered. In<br>
fact, there is such a mapping provided by<br>
importlib.machinery._get_supported_file_loaders(), but this is not a<br>
publicly documented function.<br>
<br>
One could probably think of other workarounds. For example you could<br>
implement a custom sys.meta_path hook. But I think it shouldn't be<br>
necessary to go to higher levels of abstraction in order to do<br>
this--the default sys.path handler should be able to handle this use<br>
case.<br>
<br>
In order to support adding support for new file types to<br>
sys.path_hooks, I ended up implementing the following hack:<br>
<br>
#############################################################<br>
import os<br>
import sys<br>
<br>
from importlib.abc import PathEntryFinder<br>
<br>
<br>
@PathEntryFinder.register<br>
class MetaFileFinder:<br>
"""<br>
A 'middleware', if you will, between the PathFinder sys.meta_path hook,<br>
and sys.path_hooks hooks--particularly FileFinder.<br>
<br>
The hook returned by FileFinder.path_hook is rather 'promiscuous' in that<br>
it will handle *any* directory. So if one wants to insert another<br>
FileFinder.path_hook into sys.path_hooks, that will totally take over<br>
importing for any directory, and previous path hooks will be ignored.<br>
<br>
This class provides its own sys.path_hooks hook as follows: If inserted<br>
on sys.path_hooks (it should be inserted early so that it can supersede<br>
anything else). Its find_spec method then calls each hook on<br>
sys.path_hooks after itself and, for each hook that can handle the given<br>
sys.path entry, it calls the hook to create a finder, and calls that<br>
finder's find_spec. So each sys.path_hooks entry is tried until a spec is<br>
found or all finders are exhausted.<br>
"""<br>
<br>
def __init__(self, path):<br>
if not os.path.isdir(path):<br>
raise ImportError('only directories are supported', path=path)<br>
<br>
self.path = path<br>
self._finder_cache = {}<br>
<br>
def __repr__(self):<br>
return '{}({!r})'.format(self.__class__.__name__, self.path)<br>
<br>
def find_spec(self, fullname, target=None):<br>
if not sys.path_hooks:<br>
return None<br>
<br>
for hook in sys.path_hooks:<br>
if hook is self.__class__:<br>
continue<br>
<br>
finder = None<br>
try:<br>
if hook in self._finder_cache:<br>
finder = self._finder_cache[hook]<br>
if finder is None:<br>
# We've tried this finder before and got an ImportError<br>
continue<br>
except TypeError:<br>
# The hook is unhashable<br>
pass<br>
<br>
if finder is None:<br>
try:<br>
finder = hook(self.path)<br>
except ImportError:<br>
pass<br>
<br>
try:<br>
self._finder_cache[hook] = finder<br>
except TypeError:<br>
# The hook is unhashable for some reason so we don't bother<br>
# caching it<br>
pass<br>
<br>
if finder is not None:<br>
spec = finder.find_spec(fullname, target)<br>
if spec is not None:<br>
return spec<br>
<br>
# Module spec not found through any of the finders<br>
return None<br>
<br>
def invalidate_caches(self):<br>
for finder in self._finder_cache.values():<br>
finder.invalidate_caches()<br>
<br>
@classmethod<br>
def install(cls):<br>
sys.path_hooks.insert(0, cls)<br>
sys.path_importer_cache.clear()<br>
<br>
#############################################################<br>
<br>
This works, for example, like:<br>
<br>
>>> MetaFileFinder.install()<br>
>>> sys.path_hooks.append(FileFinder.path_hook((SourceFileLoader, ['.foo'])))<br>
<br>
And now, .foo modules are importable, without breaking support for the<br>
built-in module types.<br>
<br>
This is still overkill though. I feel like there should instead be a<br>
way to, say, extend a sys.path_hooks hook based on FileFinder so as to<br>
be able to support loading other file types, without having to go<br>
above the default sys.meta_path hooks.<br>
<br>
A small, but related problem I noticed in the way FileFinder.path_hook<br>
is implemented, is that for almost *every directory* that gets cached<br>
in sys.path_importer_cache, a new FileFinder instance is created with<br>
its own self._loaders attribute, each containing a copy of the same<br>
list of (loader, extensions) tuples. I calculated that on one large<br>
project this alone accounted for nearly 1 MB. Not a big deal in the<br>
grand scheme of things, but still a bit overkill.<br>
<br>
ISTM it would kill two birds with one stone if FileFinder were<br>
changed, or there were a subclass thereof, that had a class attribute<br>
containing the standard loader/extension mappings. This in turn could<br>
simply be appended to in order to support new extension types.<br>
<br>
Thanks,<br>
E<br>
_______________________________________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org" target="_blank">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/codeofconduct/</a><br>
</blockquote></div>