Last active
June 29, 2020 02:59
-
-
Save e2thenegpii/257a1979f7bb49e7607991320c277656 to your computer and use it in GitHub Desktop.
Demonstration of a custom python package resource loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Needed for defining the finder | |
import importlib.machinery | |
# Needed to add our hook to the meta_path hook list | |
import sys | |
# To debug with pdb.set_trace() be sure to import the following before adding the meta_path | |
import pdb | |
import readline | |
class MyMetaPathFinder(importlib.machinery.PathFinder): | |
@classmethod | |
def find_spec(cls, fullname, path=None, target=None): | |
spec = super(MyMetaPathFinder, cls).find_spec(fullname, path, target) | |
if spec is not None: | |
def foo(path): | |
return b'5' | |
spec.loader.get_data = foo | |
return spec | |
# Installing our hook | |
sys.meta_path.insert(0, MyMetaPathFinder) | |
# Could have imported this above, more of a nothing up my sleeves that it still imports packages as necessary | |
import pkgutil | |
# Return a value from a non-existent package resource | |
assert b'5' = pkgutil.get_data('wheel', 'foobar') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment