Skip to content

Instantly share code, notes, and snippets.

@schlarpc
Created February 1, 2018 01:13
Show Gist options
  • Save schlarpc/e2252918587f05b1505bce3eec54ce18 to your computer and use it in GitHub Desktop.
Save schlarpc/e2252918587f05b1505bce3eec54ce18 to your computer and use it in GitHub Desktop.
# A Python 3 meta path finder for importing GitHub gists by id.
# This is a terrible idea.
# Usage:
# from gist.schlarpc import _6e0119ab5804ace6a90204137541da8e as lxmlresponse
# underscores are stripped from the gist id, but if you don't want to use that or
# if the username doesn't meet the syntax requirements then i guess you can use __import__:
# lxmlresponse = __import__('gist.schlarpc.6e0119ab5804ace6a90204137541da8e')
import importlib.abc
import importlib.machinery
import itertools
import sys
import requests
def pad_length(iterable, length, fillvalue=None):
return itertools.islice(itertools.chain(iterable, itertools.repeat(fillvalue)), length)
class GistFinder(importlib.abc.MetaPathFinder):
@staticmethod
def find_spec(fullname, path, target=None):
module, user, gist_id = pad_length(fullname.split('.'), 3)
if module != 'gist':
return None
elif gist_id:
return importlib.machinery.ModuleSpec(
fullname,
GistLoader,
)
else:
return importlib.machinery.ModuleSpec(
fullname,
None,
is_package=True,
)
class GistLoader(importlib.abc.Loader):
@staticmethod
def create_module(spec):
return None
@staticmethod
def exec_module(module):
_, user, gist_id = module.__name__.split('.')
url = 'https://gist.github.com/{}/{}/raw'.format(user, gist_id.strip('_'))
response = requests.get(url)
response.raise_for_status()
exec(response.text, module.__dict__)
sys.meta_path.append(GistFinder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment