-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_hook.py
More file actions
73 lines (51 loc) · 1.63 KB
/
import_hook.py
File metadata and controls
73 lines (51 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import sqlite3
from importlib.machinery import ModuleSpec
foo_code = """
print("foo is being initialized!")
def add(a, b):
return a + b
"""
bar_code = """
print("bar is being initialized")
def sub(a, b):
return a - b
"""
spam_code = """
print("spam is being initialized")
def fib(n: int):
if n in (0, 1):
return n
return fib(n-1) + fib(n-2)
"""
def create_repo_table():
con = sqlite3.connect(":memory:")
cursor = con.cursor()
cursor.execute("create table repository (fullname, source_code)")
cursor.executemany(
"insert into repository values (?, ?)",
[("foo", foo_code), ("bar", bar_code), ("spam", spam_code)],
)
con.commit()
return cursor
class DBImporter:
def __init__(self, cursor: sqlite3.Cursor):
self.cursor = cursor
def find_spec(self, fullname: str, path, target):
# Query database to see if we have the `fullname` module
self.cursor.execute("select 1 from repository where fullname = ?", (fullname,))
if self.cursor.fetchone():
return ModuleSpec(fullname, self)
# We don't have it in the database, go look elsewhere
return None
def create_module(self, _module_name):
# Let Python create the module, because we're too lazy
return None
def exec_module(self, module):
self.cursor.execute(
"select source_code from repository where fullname = ?", (module.__name__,)
)
source_code = self.cursor.fetchone()
exec(source_code[0], module.__dict__)
import sys
cursor = create_repo_table()
sys.meta_path.insert(0, DBImporter(cursor=cursor))